Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/67.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 获取多态关联中所有属于模型的列表_Ruby On Rails_Ruby On Rails 4_Polymorphic Associations - Fatal编程技术网

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