2012-01-28 70 views
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}} 

但寫這樣我認爲是更費時間。

+0

如果您執行User.last!.companies會發生什麼情況? – 2012-01-28 07:38:46

回答

1

以下(未測試)範圍查找給定用戶已經工作的所有公司。

class Company 
    has_many :employments 
    has_many :users, :through => :employments, :dependent => :destroy 

    scope :with_user, lambda { |user_id| joins(:employments).where(:user => user_id) } 
    ... 

運行rails c和執行嘗試Company.with_user(User.last!.id)看看會發生什麼。

相關問題