Ruby on Rails中带有嵌套资源的多态注释



我已经按照下面的Go Rails教程设置了带有多态关联的注释:https://gorails.com/episodes/comments-with-polymorphic-associations

然而,我有一个嵌套的情况,有两个模型(电影/零件(。它适用于"电影",但我无法将其用于儿童模型的"零件"。

型号

class Comment < ApplicationRecord
belongs_to :user
belongs_to :commentable, polymorphic: true
end

class Movie < ApplicationRecord
has_many :parts, dependent: :destroy
has_many :comments, as: :commentable
end
class Part < ApplicationRecord
belongs_to :movie
has_many :comments, as: :commentable
end

config/routes.rb

resources :movies do
resources :comments, module: :movies
resources :parts do
resources :comments, module: :parts
end
end

app/views/movies/show.html.erb

<%= render partial: "comments/comments", locals: {commentable: @movie} %>
<%= render partial: "comments/form", locals: {commentable: @movie} %>

app/views/comments/_comments.html.erb

<h1>Comments</h1>
<% commentable.comments.each do |comment| %>
<div class="well">
<%= comment.summary %> by <i><%= comment.user.email %></i><br><br>
</div>
<% end %>

app/views/comments/_form.html.erb

<%= form_for [commentable, Comment.new] do |form| %>
<% if commentable.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(commentable.errors.count, "error") %> prohibited this comment from being saved:</h2>
<ul>
<% commentable.errors.each do |error| %>
<li><%= error.full_message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="form-group">
<%= form.text_area :summary, class: "form-control", placeholder: "Add a comment" %>
</div>
<div class="actions">
<%= form.submit %>
</div>
<% end %>

以上关于"电影"的一切都很好。问题出在"零件"上。

app/views/parts/show.html.erb

<%= render partial: "comments/comments", locals: {commentable: @part} %>
<%= render partial: "comments/form", locals: {commentable: @part} %>

"部件"错误

零件#显示NoMethodError#ActionView::Base:0x0000000003d3b0 的未定义方法"part_comments_path">

突出显示的错误行:

<%= form_for [commentable, Comment.new] do |form| %>

我想我必须将电影对象和部分对象传递到"commentable"中——因为它是嵌套的——但不知道如何使用此设置。如有任何建议,我们将不胜感激。

我认为部分中的路由意味着用movie_part_comments_path替换对part_comment_path的任何引用。

最新更新