Fields for writing to the association "has many" inside the form

I have one Topicthat has a lot of Posts. When a topic is created, it creates the first message with it.

I have included the mail 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 mine looks like 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

I get UnknownAttributeError - unknown attribute: postin the first line of the method create. I guess this is because the message hash was included in the topic hash in the request:

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

How can I get around this?

+3
source share
1 answer
  • Your model Topicmust have accepts_nested_attributes_for :postsin it.
  • Your form should have = topic_form.fields_for :posts do |post_fields|instead @post.
  • new, create @post = ..... @topic, .

: http://ryandaigle.com/articles/2009/2/1/what-s-new-in-edge-rails-nested-attributes

+4

Source: https://habr.com/ru/post/1788652/


All Articles