1
邮政型号大厦复杂的形式和关系
class Post < ActiveRecord::Base
attr_accessible :user_id, :title, :cached_slug, :content
belongs_to :user
has_many :lineitems
def lineitem_attributes=(lineitem_attributes)
lineitem_attributes.each do |attributes|
lineitems.build(attributes)
end
end
发表观点:
<% form_for @post do |f| %>
<%= f.error_messages %>
<p>
<%= f.label :title %><br />
<%= f.text_field :title %>
</p>
<p>
<%= f.label :cached_slug %><br />
<%= f.text_field :cached_slug %>
</p>
<p>
<%= f.label :content %><br />
<%= f.text_area :content, :rows => 3 %>
</p>
<% for lineitem in @post.lineitems %>
<% fields_for "post[lineitem_attributes][]", lineitem do |lineitem_form| %>
<p>
Step: <%= lineitem_form.text_field :step %>
</p>
<% end %>
<% end %>
<p><%= f.submit %></p>
<% end %>
从控制器
12 def new
13 @user = current_user
14 @post = @user.posts.build(params[:post])
15 3.times {@post.lineitems.build}
16 end
17
18 def create
19 debugger
20 @user = current_user
21 @post = @user.posts.build(params[:post])
22 if @post.save
23 flash[:notice] = "Successfully created post."
24 redirect_to @post
25 else
26 render :action => 'new'
27 end
28 end
我目前正在与一些代码,看railscasts播放。我在73岁,并且有关于保存此表单的问题。
我粘贴了一些代码,同时跟着railscasts 73。我的代码在第20至23行关于另一个发布关系的方面略有不同。使用调试器,@post只有user_id和post值。 params包含lineitem_attributes。线条不会被保存。
如何构建帖子,包括lineitems?
我在你的答案中修正了一些问题。否则,这是我一直在寻找的答案 – 2011-03-07 09:32:09