开发者

Building complex forms and relationships

Post Model

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

Post View:

<% 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 %>
  开发者_StackOverflow</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 %>

From the controller

 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

I am currently playing with some code and watching railscasts. I am on 73 and have a question about saving this form.

I have pasted some code and while following railscasts 73. My code is a bit different at around line 20 to 23 regarding another post relationship. Using debugger, @post only has the user_id and the post values. params contains the lineitem_attributes. The lineitems do not get saved.

How do I build the post including the lineitems?


Many of the earlier railscasts are outdated now. The standard way of doing this these days is by using nested attributes. There's a railscast on this topic in two parts: Part 1 and part 2. There isn't much I can add that the screencasts don't cover except that your code will be a lot simpler:

class Post < ActiveRecord::Base

  attr_accessible :user_id, :title, :cached_slug, :content
  belongs_to :user
  has_many :lineitems

  accepts_nested_attributes_for :lineitems
end

I can't remember offhand how this works with protected attributes, but you may need to add :lineitems_attributes to attr_accessible

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜