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?
- Your
Topicmodel should have aaccepts_nested_attributes_for :postsin it. - Your form should have
= topic_form.fields_for :posts do |post_fields|instead of@post. - Neither your
newnor yourcreatemethods need the@post = ....lines. When you save the@topicit 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
加载中,请稍侯......
精彩评论