2011-03-07 67 views
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?

回答

1

許多較早的railscast已經過時了。現在這樣做的標準方式是使用嵌套屬性。這個主題有兩個部分的railscast:Part 1part 2。沒有多少,我可以補充的是,截屏不只是你的代碼會簡單得多覆蓋:

class Post < ActiveRecord::Base 

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

    accepts_nested_attributes_for :lineitems 
end 

我不記得的副手是如何工作與保護屬性,但您可能需要將:lineitems_attributes添加到attr_accessible

+0

我在你的答案中修正了一些問題。否則,這是我一直在尋找的答案 – 2011-03-07 09:32:09