Mel*_*orn 0 ruby-on-rails erb nested-forms
目标:保存构思模型的评论.
形成:
<%= form_for([@idea, IdeaComment.new], :validate => true) do |f| %>
<div class="control-group">
<div class="controls">
<%= f.text_area :text, :placeholder => 'some text', :rows => 5 %>
<%= validate_errors(IdeaComment.new) %>
</div>
</div>
<%= f.button 'Comment', :class => 'button grad-green', :type => 'submit' %>
<% end %>
Run Code Online (Sandbox Code Playgroud)
控制器:
@idea_comment = IdeaComment.new(params[:idea_comment])
...
Run Code Online (Sandbox Code Playgroud)
但是如果我们看看params hash:

如何将idea_id传递给"idea_comment"?
客户端验证与面向资源的表单相冲突.请改用常规服务器端验证.
面向资源的表单基于嵌套资源发布到路径:
form_for([@idea, IdeaComment.new]) # => POST '/ideas/[:idea_id]/idea_comments'
Run Code Online (Sandbox Code Playgroud)
Rails :idea_id从请求路径中提取并将其作为参数传递.在create操作中,关联在保存之前通过直接分配设置:
# controllers/idea_comments_controller.rb
def create
@idea_comment = IdeaComment.new(params[:idea_comment])
@idea_comment.idea_id = params[:idea_id]
# ...
@idea_comment.save
end
Run Code Online (Sandbox Code Playgroud)
客户端验证的问题在于它将失败并阻止表单提交,直到@idea_comment.idea_id分配,这在表单提交之后才会发生.