提问人:spinachbro 提问时间:12/28/2021 最后编辑:Eyeslandicspinachbro 更新时间:12/28/2021 访问量:304
Ruby on Rails 中使用嵌套资源的多态注释
Polymorphic comments with nested resources in 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
配置/routes.rb
resources :movies do
resources :comments, module: :movies
resources :parts do
resources :comments, module: :parts
end
end
应用/视图/电影/显示:.html.erb
<%= render partial: "comments/comments", locals: {commentable: @movie} %>
<%= render partial: "comments/form", locals: {commentable: @movie} %>
应用/视图/评论/_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 %>
上面的“电影”一切都运行良好。问题出在“零件”上。
应用程序/视图/零件/显示:.html.erb
<%= render partial: "comments/comments", locals: {commentable: @part} %>
<%= render partial: "comments/form", locals: {commentable: @part} %>
“parts”错误
NoMethodError in Parts#显示 #ActionView::Base:0x0000000003d3b0 的未定义方法“part_comments_path”
突出显示的错误行:
<%= form_for [commentable, Comment.new] do |form| %>
我想我必须将带有部分对象的电影对象传递到“commentable”中——因为它是嵌套的——但不知道如何使用这种设置来做到这一点。任何建议将不胜感激。
答:
-1赞
Nestor Pestelos
12/28/2021
#1
我相信部分路线意味着用movie_part_comments_path替换任何对part_comments_path的引用。
评论
rake routes
part_comments
movie_part_comments_path
/part/comments/
/movies/part/comments/
movie
part