Ruby on rails 通过具有唯一来源的多个模型进行了多次测试
举一个大家都熟悉的例子,想想StackOverflow。 用户Ruby on rails 通过具有唯一来源的多个模型进行了多次测试,ruby-on-rails,activerecord,associations,Ruby On Rails,Activerecord,Associations,举一个大家都熟悉的例子,想想StackOverflow。 用户有很多:问题,有很多:答案,她的问题和答案可能会被评论。(注释是多态的) 我希望通过对该用户的问题或答案的评论,获得针对该用户的所有回复: class User < ActiveRecord::Base has_many :questions has_many :answers has_many :comments has_many :responses, through: [:questions, :answe
有很多:问题
,有很多:答案
,她的问题和答案可能会被评论。(注释是多态的)
我希望通过对该用户的问题或答案的评论,获得针对该用户的所有回复:
class User < ActiveRecord::Base
has_many :questions
has_many :answers
has_many :comments
has_many :responses, through: [:questions, :answers], source: :comments
end
class Question < ActiveRecord::Base
belongs_to :user
has_many :answers
has_many :comments, as: :commentable
end
class Answer < ActiveRecord::Base
belongs_to :user
belongs_to :question
has_many :comments, as: :commentable
end
class Comment < ActiveRecord::Base
belongs_to :commentable, polymorphic: true
end
class用户
当然,有很多:答案,通过:[:问题,答案],source::comments
不起作用
有什么办法吗
谢谢。我想这里已经回答了这个问题:@DGM谢谢,但遗憾的是没有。顺便说一句,接受的答案确实不是IMO应该做的事情。在Association中编写sql条件如何?我发现了另一个技巧@Damien hello,只是想知道您是否找到了问题的解决方案?
has_many :responses, :class_name => "Comment", :finder_sql =>
'SELECT DISTINCT comments.* ' +
'FROM comments c, questions q, answers a ' +
'WHERE (c.commentable_id = a.id and c.commentable_type='Answer' and a.user_id = #{id} ) or (c.commentable_id = q.id and c.commentable_type='Question' and q.user_id = #{id})'