2011-01-29 34 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

相关问题