gpt4 book ai didi

ruby-on-rails - has_many 通过具有唯一来源的多个模型

转载 作者:行者123 更新时间:2023-12-04 03:44:15 24 4
gpt4 key购买 nike

举一个大家都熟悉的例子,想想 StackOverflow。
某用户 has_many :questions , has_many :answers她的问题和答案可能会被评论。 (评论是多态的)。

我想通过对该用户的问题或答案的评论来获得针对特定用户的所有回复:

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

当然, has_many :responses, through: [:questions, :answers], source: :comments不起作用。

有 Rails 的方法吗?

谢谢。

最佳答案

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})'

关于ruby-on-rails - has_many 通过具有唯一来源的多个模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8509377/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com