2011-12-14 20 views
7

Để có một ví dụ mọi người quen thuộc, hãy nghĩ về StackOverflow. Một người dùng has_many :questions, has_many :answers và các câu hỏi và câu trả lời của cô ấy có thể được nhận xét. (Nhận xét là đa hình).has_many thông qua nhiều mô hình với một nguồn duy nhất

Tôi muốn có được tất cả các câu trả lời gửi đến một người dùng cụ thể thông qua một bình luận trên một trong hai câu hỏi hay câu trả lời của thành viên này:

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 

Tất nhiên, has_many :responses, through: [:questions, :answers], source: :comments không hoạt động.

Có cách nào để Rails làm điều đó không?

Cảm ơn.

+0

Tôi nghĩ rằng điều này đã được trả lời ở đây: http://stackoverflow.com/questions/3487730/reverse-polymorphic-associations – DGM

+0

@DGM Cảm ơn, nhưng thật đáng buồn không. Nhân tiện, câu trả lời được chấp nhận thực sự không phải là điều đúng để làm IMO. – Damien

+0

làm thế nào về viết điều kiện sql trong assocation? – blade

Trả lời

1
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})' 
Các vấn đề liên quan