2011-12-14 14 views
7

Per fare un esempio con cui tutti hanno familiarità, pensa a StackOverflow. Un utente has_many :questions, has_many :answers e le sue domande e risposte possono essere commentati. (Il commento è polimorfico).has_many attraverso più modelli con una fonte univoca

voglio ottenere tutte le risposte rivolte a un particolare utente tramite un commento su entrambi domande o risposte di questo utente:

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 

Naturalmente, has_many :responses, through: [:questions, :answers], source: :comments non funziona.

Esiste un modo Rails per farlo?

Grazie.

+0

penso che questo è stato risposto qui: http://stackoverflow.com/questions/3487730/reverse-polymorphic-associations – DGM

+0

@DGM Grazie ma purtroppo non. A proposito, la risposta accettata non è davvero la cosa giusta da fare IMO. – Damien

+0

come definire le condizioni di scrittura sql in associazione? – blade

risposta

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