Ruby on rails Rails:多态关联,查找评论

Ruby on rails Rails:多态关联,查找评论,ruby-on-rails,ruby,polymorphic-associations,Ruby On Rails,Ruby,Polymorphic Associations,我已经在我的Rails应用程序上使用实现了多态注释 因此,我: class Place < ApplicationRecord has_many :comments, as: :commentable end class Comment < ApplicationRecord belongs_to :commentable, polymorphic: true end 在我的评论index.html.erb中,我可以访问: <%= comment.commentab

我已经在我的Rails应用程序上使用实现了多态注释

因此,我:

class Place < ApplicationRecord
  has_many :comments, as: :commentable
end

class Comment < ApplicationRecord
  belongs_to :commentable, polymorphic: true
end
在我的评论
index.html.erb
中,我可以访问:

<%= comment.commentable_type %>
<%= comment.commentable_id %>

但是如何访问注释的实际属性,例如:


我相信这与这个答案有关,但我不知道怎么说:

mccalljt上面的答案要好得多

相信我已经做到了:

添加到
comment.rb

belongs_to :place, foreign_key: 'commentable_id'
@comments = Comment.where(commentable_type: "Place").joins(:place)
添加到
注释\u controller.rb

belongs_to :place, foreign_key: 'commentable_id'
@comments = Comment.where(commentable_type: "Place").joins(:place)
虽然当有更多关联时,这是不可重用的,但我可以将其更改为:

@place_comments = Comment.where(commentable_type: "Place").joins(:place)
@other_comments = Comment.where(commentable_type: "Other").joins(:other)

您可以使用

comment.commentable
这里唯一需要注意的是,它假设您的所有注释都有您调用的方法,例如
name

comment.commentable.name
您将希望在控制器中预加载这些,以避免N+1

class CommentsController < ApplicationController
  def index
    @comments = Comment.includes(:commentable).all
  end
end
class CommentsController
完美。显示它如何避免N+1:Without
t.includes(:commentable)。all
对每个有注释的位置执行
SELECT
。使用
t.includes(:commentable)。all
它使用
在(7,9)
中的“places.”id“位置执行单个
选择。