2
我需要編寫一個範圍,我將傳遞一個用戶ID,並從users
表中收集該用戶的所有公司的所有用戶列表關聯。如何爲多對多關係中的某個對象編寫作用域?
在User.rb:
has_many :employments
has_many :companies, :through => :employments, :dependent => :destroy
...
在Employment.rb:
belongs_to :user
belongs_to :company
在Company.rb:
:has_many :employments
has_many :users, :through => :employments, :dependent => :destroy
這可能會使用類似可能
current_user.companies.each{|c| c.users.each {|u| u}}
但寫這樣我認爲是更費時間。
如果您執行User.last!.companies會發生什麼情況? – 2012-01-28 07:38:46