0

2 つのモデル、たとえばとhas_and_belongs_to_manyの間に関係がある場合、 に少なくとも 1 つの があることを要求できますか? また、その方法は?UsersAccountsUserAccount

また、has_and_belongs_to_many関係を使用して、Accountが を持たないことは可能Userですか?

私が必要としているのは、一人でAccounts生きて、所属できる関係ですが、サインアップすればBillers所属することもできます。これは可能ですか?UsersUser

4

2 に答える 2

0

個人的には、HABTM を削除します。代わりに私は使用しますhas_many :though=>

account_users と account_billers という 2 つの新しいモデルを作成する必要があります。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
于 2012-07-12T19:35:24.173 に答える
0

少なくとも 1 つの関連付けの存在を検証するには、次のようなカスタム検証メソッドを使用することをお勧めします。

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

(これは、アカウントがユーザー間でどのように共有されているかという問題をもたらしますが)

2 番目の質問については、ポリモーフィック アソシエーションが探しているもののように見えますが、HABTM リレーションシップではこれを直接行うことはできません。それを に変更してhas_many :through結合モデルを導入する必要があります。

于 2012-07-12T19:35:56.103 に答える