2011-03-28 13 views
9

Ho inchiodato quello che voglio, ma non riesco a farlo in modo che i designer di binari stiano cercando. Fondamentalmente, ho (si prega di mettere da parte pluralizzazione/problemi etc.):Has_Many: Through o: finder_sql

umana Relationships (Genitori, Figli)

Sto cercando di ottenere tutti i discendenti di un solo genitore, e il singolo genitore per molti progenie (si presume un solo genitore per discendenza).

posso fare questo nel modo seguente nel modello:

has_one  :parent, :through => :relationships, :foreign_key => :human_id, :source => :source_human 
has_many :offsprings, :finder_sql => 
      'SELECT DISTINCT offsprings.* ' + 
      'FROM humans offsprings INNER JOIN relationships r on ' + 
      'r.human_id = offsprings.id where r.source_human_id = #{id}' 

ho dovuto fare questo, perché il modo più bello per farlo:

has_many :offsprings, :through => :relationships, :foreign_key => :source_human_id, :source => :human 

non è possibile perché le chiavi esterne sono ignorati in has_many (secondo la documentazione qui: http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-has_many)

Tuttavia, ora sto ottenendo questo errore:

Tuttavia, a prescindere da come mi attacco: condizioni qui, non sembra che: finder_sql vuole partecipare. qualche idea?

risposta

35

Che cosa succede se si fa

has_many :offsprings, :finder_sql => 
      proc { "SELECT DISTINCT offsprings.* " + 
      "FROM humans offsprings INNER JOIN relationships r on " + 
      "r.human_id = offsprings.id where r.source_human_id = #{id}" } 
+2

Ladies and Germs, un vincitore. I documenti sono sbagliati qui, non devi fare una: condizioni su: finder_sql, devi solo costruirla. – aronchick

4

In realtà, mi piacerebbe scrivere in questo modo:

has_many :offsprings, :finder_sql => proc {OFFSPRING_SQL % {id: id}} 

OFFSPRING_SQL = "SELECT DISTINCT offsprings.* 
        FROM humans offsprings 
        INNER JOIN relationships r 
         ON r.human_id = offsprings_id 
         WHERE r.source_human_id = %{id}" 

penso che rende l'associazione più facile da capire, e faccio lo SQL naked più facile modificare. Sfrutta inoltre l'interpolazione dei parametri basata su stringhe.

Problemi correlati