开发者

Fields for a record in a 'has many' association inside a form

I have a Topic that has many Posts. When a topic is created, it creates the first post along with it.

I included the post fields in the form:

= 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/

Here's what my TopicsController looks like:

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

I get an UnknownAttributeError - unknown attribute: post o开发者_JS百科n the first line of the create method. I'm guessing it's because the post hash was included in the topic hash in the request:

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

How can I work around this situation?


  1. Your Topic model should have a accepts_nested_attributes_for :posts in it.
  2. Your form should have = topic_form.fields_for :posts do |post_fields| instead of @post.
  3. Neither your new nor your create methods need the @post = .... lines. When you save the @topic it will automatically save the new associated post for you.

Here's a great explanation of nested attributes in forms: http://ryandaigle.com/articles/2009/2/1/what-s-new-in-edge-rails-nested-attributes

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜