【问题标题】:Having trouble submitting nested resource through form [Rails 5]通过表单提交嵌套资源时遇到问题 [Rails 5]
【发布时间】:2019-05-24 23:33:53
【问题描述】:

我有一个Documenthas_manySection,每个sectionhas_oneComment。我希望能够在 Document show 视图中同时创建 sectionscomments,但我无法让 comments 通过。

这是我所拥有的最接近的相关代码:

class CommentsController < ApplicationController
  def create
    @section = Section.find(params[:id])
    @section.comment.create(comment_params)
  end

  private

    def comment_params
      params.require(:comment).permit(:body)
    end
end

路由:

resources :documents, shallow: true do
  resources :sections do
    resources :comments
  end
end 

以及带有表单的视图:

# app/views/documents/show.html.erb

<% @document.sections.each do |section| %>
  <%= section.body %>

  <% if section.comment %>
    <p>
      <%= section.comment %>
    </p>
  <% else %>
    <%= form_with url: section_comments_path(section.id), scope: 'comment' do |form| %>
      <%= form.text_field :body, placeholder: "Comment" %>
      <%= form.submit %>
    <% end %>
  <% end %>
<% end %>

这一切似乎都适合我,但是当我尝试发表评论时,我得到了以下信息:

Started POST "/sections/51/comments" for ::1 at 2019-05-24 23:29:06 +0000
Processing by CommentsController#create as JS
  Parameters: {"utf8"=>"✓", "authenticity_token"=>[...], "comment"=>{"body"=>"asdas"}, "commit"=>"Save comment", "section_id"=>"51"}
  Section Load (0.5ms)  SELECT  "sections".* FROM "sections" WHERE "sections"."id" = ? LIMIT ?  [["id", 51], ["LIMIT", 1]]
  comment Load (0.4ms)  SELECT  "comments".* FROM "comments" WHERE "comments"."section_id" = ? LIMIT ?  [["section_id", 51], ["LIMIT", 1]]
Completed 500 Internal Server Error in 11ms (ActiveRecord: 0.9ms)

NoMethodError (undefined method `create' for nil:NilClass):

app/controllers/comments_controller.rb:4:in `create'

有什么想法吗?

【问题讨论】:

  • 由于 cmets 嵌套在路由中的部分下,因此您应该在创建操作中找到 params[:section_id] 而不是 params[:id] 中的部分。

标签: ruby-on-rails forms ruby-on-rails-5 nested-resources


【解决方案1】:

has_one 关系返回对象本身。因此,@section.comment.create(comment_params) 将不起作用,因为@section.comment 为零。相反,尝试类似...

def create
  @section = Section.find(params[:section_id])
  @comment = Comment.create(comment_params)
  @section.comment = @comment

  ...
end

或者,如 Rails 指南中所述...

当初始化一个新的 has_one 或 belongs_to 关联时,你必须使用 构建关联的 build_ 前缀,而不是 将用于 has_many 或的 association.build 方法 has_and_belongs_to_many 关联。要创建一个,请使用 create_ 前缀。

看起来像这样

def create
  @section = Section.find(params[:section_id])
  @section.create_comment(comment_params)

  ...
end

【讨论】:

  • 我最终做了一些改变,并让它以某种方式工作,所以我不能 100% 确定它做了什么,但我现在用 @section.create_comment(comment_params) 尝试了它,它仍然有效,所以我我正在接受答案。谢谢!
【解决方案2】:

你可能需要改变:

@section.comment.create(comment_params)

到:

@section.comments.create(comment_params)

如果这不起作用,请尝试:

@section.comment.create!(comment_params)

看看异常说明了什么

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-13
    • 2011-05-25
    • 2016-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多