0

如果我有兩個模型之間的關係has_and_belongs_to_many,比方說UsersAccounts,我可以要求一個User至少有一個Account,又如何呢?Rails的做一個模型需要另一種模式

此外,使用has_and_belongs_to_many關係,Account可能不具有User

我需要的是在那裏Accounts可以生活在自己,屬於Billers的關係,但他們也可以屬於Users如果User一個報了名。這是可能的,以及如何?

回答

0

我個人會放棄HABTM。相反,我會使用has_many :though=>

您需要創建兩個新模型,account_users和account_billers。您可能已經有了HABTM的連接表,但是這會將它們暴露爲模型,因此它們將需要ID字段。

所以,你最終會像下面這樣:

class Account < ActiveRecord::Base 
    has_many :account_billers 
    has_many :account_users 

    has_many :billers, :through=> :account_billers 
    has_many :users, :through=> :account_users 
end 

class User < ActiveRecord::Base 
    has_many :account_users 
    has_many :accounts, :through=>:account_users 

    validates :accounts, :length => { :minimum => 1} 
end 

class Biller < ActiveRecord::Base 
    has_many :account_billers 
    has_many :accounts, :through=>:account_billers 

    validates :accounts, :length => { :minimum => 1} 
end 

class AccountUser < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :account 
end 

class AccountBiller < ActiveRecord::Base 
    belongs_to :biller 
    belongs_to :account 
end 
+0

這將設置一個要求,即用戶和賬單持有人擁有賬戶,但賬戶可能無法擁有用戶或賬單持有人。 – 2012-07-12 19:36:55

0

要驗證至少一種關聯的存在,你可能想使用一個custom validation method,像

class User < ActiveRecord::Base 
    has_and_belongs_to_many :accounts 
    validate :require_at_least_one_account 

    private 
    def require_at_least_one_account 
     errors.add(:accounts, "must amount to at least one") if accounts.size < 1 
    end 
end 

(雖然這帶來了如何在用戶之間共享帳戶的問題)

對於第二個問題,看起來像polymorphic associations是wha你正在尋找,但你不能直接與HABTM的關係做到這一點,你必須將其改爲has_many :through並引入聯合模型。

+0

你可以使用多態,但沒有好的方法來做多態的FK約束。如果user1521444對模型和關係還沒有很好的把握,我會避免這種情況。 – 2012-07-13 01:43:05

+0

有了多態關聯,看起來好像您可以擁有一個屬於用戶或Biller的帳戶,但同一個帳戶是否屬於多態關聯? – macdamaniac 2012-07-13 16:13:57

+0

如果您可以同時擁有屬於用戶和賬單的賬戶,我不認爲AR支持這種開箱即用的方式。你可以檢查這個問題http://stackoverflow.com/questions/3209322/rails-polymorphic-has-many – HargrimmTheBleak 2012-07-13 16:23:41

相關問題