Ruby on rails 获取多态关联中所有属于模型的列表
我有这两种型号:Ruby on rails 获取多态关联中所有属于模型的列表,ruby-on-rails,ruby-on-rails-4,polymorphic-associations,Ruby On Rails,Ruby On Rails 4,Polymorphic Associations,我有这两种型号: class Review < ActiveRecord::Base belongs_to :reviewable, polymorphic: true end class Article < ActiveRecord::Base has_one :review, as: :reviewable, dependent: :destroy end 对于一篇评论,我只想这样做: @review = Review.where("user_id = ?",
class Review < ActiveRecord::Base
belongs_to :reviewable, polymorphic: true
end
class Article < ActiveRecord::Base
has_one :review, as: :reviewable, dependent: :destroy
end
对于一篇评论,我只想这样做:
@review = Review.where("user_id = ?", current_user.id).first
@article = @review.article
但是,我现在如何从@reviews列表中获得与这些评论相关的所有文章的列表呢?如果
@article=@review.article
代码起作用,那么您只需询问如何迭代一组评论?那么
@reviews = Review.where("user_id = ?", current_user.id)
# in your view
@reviews.each do |review|
review.article
end
你可以:
如果您的意思是列出所有与您的任何模型相关的模型。你的答案在这里很清楚;
您可以调用:has\u many或:has\u one associations too您可以加载这些关联
@reviews = Review.where("user_id = ?", current_user.id).includes(:reviewable)
若你们真的需要所有的评论,你们可以:-
@reviewables = @reviews.map(&:reviewable).uniq
Thing.reflections.collect{|a, b| b.class_name if b.macro==:belongs_to}.compact
@reviews = Review.where("user_id = ?", current_user.id).includes(:reviewable)
@reviewables = @reviews.map(&:reviewable).uniq