Ruby on rails 在RubyonRails中以嵌套形式传递父id

Ruby on rails 在RubyonRails中以嵌套形式传递父id,ruby-on-rails,nested-forms,erb,Ruby On Rails,Nested Forms,Erb,目标:为idea模型保存注释 表格: <%= form_for([@idea, IdeaComment.new], :validate => true) do |f| %> <div class="control-group"> <div class="controls"> <%= f.text_area :text, :placeholder => 'some text

目标:为idea模型保存注释

表格:

<%= 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 %>
 @idea_comment = IdeaComment.new(params[:idea_comment])
 ...
但如果我们看一下params散列:


如何将idea\u id传递给“idea\u comment”?

客户端验证与面向资源的表单相冲突。改用常规服务器端验证

说明: 基于嵌套资源将面向资源的表单发布到路径:

form_for([@idea, IdeaComment.new]) # => POST '/ideas/[:idea_id]/idea_comments'
Rails从请求路径中提取
:idea\u 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

客户端验证的问题是,它将失败并阻止表单提交,直到
@idea\u comment.idea\u id
被分配,这在表单提交之后才会发生。

客户端验证与面向资源的表单相冲突。改用常规服务器端验证

说明: 基于嵌套资源将面向资源的表单发布到路径:

form_for([@idea, IdeaComment.new]) # => POST '/ideas/[:idea_id]/idea_comments'
Rails从请求路径中提取
:idea\u 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

客户端验证的问题是,它将失败并阻止表单提交,直到
@idea\u comment.idea\u id
被分配,这在表单提交之后才会发生。

您不需要这样做。为什么要尝试?当我尝试使用params[:idea_comment]保存模型时出现错误,idea_id不能为null。显示相应的代码吗?您可能正在执行类似于
IdeaComment.create(params[:idea\u comment])
的操作,而不是
@idea.idea\u comments.create(params[:idea\u comment])
。您不需要这样做。为什么要尝试?当我尝试使用params[:idea_comment]保存模型时出现错误,idea_id不能为null。显示相应的代码吗?您可能正在执行类似于
IdeaComment.create(params[:idea\u comment])
的操作,而不是
@idea.idea\u comments.create(params[:idea\u comment])
。很好的解释。谢谢,很好的解释。谢谢