2008年5月7日 星期三

db associations has_many through source class_name

http://blog.hasmanythrough.com/2007/10/30/self-referential-has-many-through
http://blog.hasmanythrough.com/2006/4/21/self-referential-through



class User
has_many :reading
end

class Reading
belongs_to :user
belongs_to :article
end

class Article
(後面兩個參數foreign_key, class_name 因符合rails的命名規則, 所以都可省略)
has_many :readings, :foreign_key => article_id, :class_name => Reading

(透過through => :readings, 從readings 那邊就可以取得user的 association)
has_many :users, :through => :readings

(正常像上面那樣就可以了, 但如果想要自己取有意義的association name 可以用source)
has_many :readers, :through => :readings, :source => :user

(還可以下條件)
has_many :readers, :through => :readings, :source => :user, :conditions => 'readings.rating > 4'
end

沒有留言: