2011-01-29 32 views
3

我有一個Topic有很多Post s。當創建主題時,它會創建第一篇文章。記錄在'有很多'協會在一個表格內的字段

我包含在表單中後場:

= form_for @topic do |topic_form| 

    # ... 

    = topic_form.fields_for @post do |post_fields| 
    = post_fields.label :content 
    %br/ 
    = post_fields.text_area :content 
    %br/ 

這裏是我的TopicsController是什麼樣子:

def new 
    @topic = Topic.new 
    @post = Post.new 
    respond_with @topic 
end 

def create 
    @topic = Topic.create params[:topic] 
    @post = @topic.create_post params[:topic][:post] 
    respond_with @topic, location: topic_url(@topic) 
end 

我在create方法的第一線得到UnknownAttributeError - unknown attribute: post。我猜這是因爲後散列包含在請求中的主題散列中:

"topic" => { "title" => "...", "post" => { "content" => "..." } } 

我該如何解決這種情況?

回答

4
  1. 您的Topic模型應該有一個accepts_nested_attributes_for :posts在其中。
  2. 您的表單應該有= topic_form.fields_for :posts do |post_fields|而不是@post
  3. 您的newcreate方法都不需要@post = ....行。當您保存@topic時,它會自動爲您保存新的相關帖子。

這裏的嵌套屬性的表單中的一個很好的解釋:http://ryandaigle.com/articles/2009/2/1/what-s-new-in-edge-rails-nested-attributes

+0

我做的指示,但我仍然得到完全相同的錯誤。 – 2011-01-29 06:58:54

相關問題