I have two models,
我有两个模型,
class User < ActiveRecord::Base
has_many :posts
end
class Post < ActiveRecord::Base
belongs_to: user
end
I'm using formtastic gem
, consider in edit
action of users_controller
. All required user
and associated posts
attributes of the form will be prefilled by formtastic form
我使用的是formtastic gem,请考虑users_controller的编辑操作。表单的所有必需的用户和相关的贴子属性都将使用formtastic表单进行预填充
code:
代码:
<%= semantic_form_for @user do |f| %>
<%= f.input :name %>
<%= f.inputs :posts do |p| %>
<%= p.input :title %>
<%= p.input :comment %>
<% end %>
<% end %>
For instance i'm having a @user
and two posts
associated. while doing @user.posts
, the result be like.
例如,我有一个@user和两个相关的帖子。在做@user。贴吧,结果就像。
[
[0] #<Post:0x0000000aa53a20> {
:id => 3,
:title => 'Hello World',
:comment => 'Long text comes here'
},
[1] #<Post:0x0000000aa53a41> {
:id => 5,
:title => 'Hello World 2',
:comment => 'Long text comes here too'
}
]
So the form will contain two posts field to edit.
因此,表单将包含两个要编辑的posts字段。
Actually, I want another blank post form before those two posts.
实际上,在这两篇文章之前,我想再要一份空白的表格。
This can be easy achieved by inserting a new empty post
object to @object.posts
result at 0th position.
这可以通过向@object插入一个新的空post对象来实现。职位排名第0位。
So, the @object.posts
result i want should exactly look like,
所以,@object。post结果我想要的应该是,
[
[0] #<Post:0x0000000aa53a50> {
:id => nil,
:title => nil,
:comment => nil
},
[1] #<Post:0x0000000aa53a20> {
:id => 3,
:title => 'Hello World',
:comment => 'Long text comes here'
},
[2] #<Post:0x0000000aa53a41> {
:id => 5,
:title => 'Hello World 2',
:comment => 'Long text comes here too'
}
]
Any solutions to get this structure from @user.posts
?
从@user.posts获得此结构的解决方案?
1 个解决方案
#1
2
Inside the #edit
action do something like :
在#edit操作中,做如下操作:
def edit
#... your code
@user.posts << Post.new
end
#1
2
Inside the #edit
action do something like :
在#edit操作中,做如下操作:
def edit
#... your code
@user.posts << Post.new
end