2014-03-30 22 views
2

我有2個車型UserBusiness。許多用戶可以擁有一項業務,用戶可以擁有多項業務。導軌的has_many雖然協會 - 指定鍵名

用戶也可以是企業或客戶的員工。

但只是專注於我一直有麻煩,因爲我試圖使用用戶ID,而將其稱爲一個所有者所有者業務關聯。

我已經成立了一個BussinessesOwners連接表,並有以下型號:

class User < ActiveRecord::Base 
    has_many :businesses, through: :businesses_owners 
end 

class Business < ActiveRecord::Base 
    has_many :owners, :class_name => 'User', :foreign_key => "owner_id", through: :businesses_owners 
end 

class BusinessesOwners < ActiveRecord::Base 
    belongs_to :users, :foreign_key => "owner_id" 
    belongs_to :businesses 
end 

BusinessesOwners遷移:

class CreateBusinessOwners < ActiveRecord::Migration 
    def change 
    create_table :business_owners, :id => false do |t| 
     t.integer :business_id 
     t.integer :owner_id 
    end 
    end 
end 

我如何建立該協會是指用戶模型業主? - 那麼Businesses.owners會返回一個用戶列表?

回答

3

個人而言,我喜歡根據關聯表命名關聯,換句話說:user_id而不是owner_id。而且,由於你是不是做一個HABTM關係,你不綁定到「buisinesses_owners」約定,你可以給通過模型一個更好的名字,如BusinessOwnership甚至Ownership(例如,如果多態用於用戶之間的任何所有制關係和另一種型號)。

請注意,在通過模型的belongs_to必須是單數。 (閱讀協會出聲,你會聽到它沒有意義的,多在這裏使用。)

下列因此應該工作:

class User < ActiveRecord::Base 
    has_many :businesses, through: :business_ownerships 
    has_many :business_ownerships 
end 

class Business < ActiveRecord::Base 
    has_many :owners, through: :business_ownerships, source: :user 
    has_many :business_ownerships 
end 

class BusinessOwnership < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :business 
end 

而且這裏的遷移:

class CreateUsers < ActiveRecord::Migration 
    def change 
    create_table :users do |t| 
     t.string :name 
    end 
    end 
end 

class CreateBusinesses < ActiveRecord::Migration 
    def change 
    create_table :businesses do |t| 
     t.string :name 
    end 
    end 
end 

class CreateBusinessOwnerships < ActiveRecord::Migration 
    def change 
    create_table :business_ownerships do |t| 
     t.references :user 
     t.references :business 
    end 
    end 
end 

請注意:除非您爲BusinessOwnership添加額外的屬性,或者將其作爲多態性Ownership模型回收,否則在此處執行「has_many through」並不是必須的,您也可以對HABTM與根據相應的con vention。

+0

這就是答案,我認爲 - 我可以解釋爲什麼,如果你需要 –

+0

大回答它的作品!我需要做些什麼才能使它與'CreateBusinessOwnerships'列一起被命名爲':user_id'&'business_id'? –

+1

就是這樣的:'t.references:user'是一個更加語義化的方式來說't.integer:user_id'。 – svoop