【问题标题】:Rails make a model require another modelRails 使一个模型需要另一个模型
【发布时间】:2012-07-12 15:06:49
【问题描述】:

如果我在两个模型之间有has_and_belongs_to_many 关系,比如说UsersAccounts,我是否可以要求User 至少有一个Account,以及如何?

另外,使用has_and_belongs_to_many 关系,Account 是否有可能没有User

我需要的是一种Accounts 可以独立生活并属于Billers 的关系,但如果User 与之签约,他们也可以属于Users。这可能吗?如何实现?

【问题讨论】:

    标签: ruby-on-rails database-design activerecord model database-relations


    【解决方案1】:

    我个人会放弃 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
    

    【讨论】:

    • 这将设置用户和帐单有帐户的要求,但帐户可以在没有用户或帐单的情况下存在。
    【解决方案2】:

    要验证是否存在至少一个关联,您可能需要使用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 是您要查找的内容,但您不能直接通过 HABTM 关系执行此操作,您必须将其更改为 has_many :through 并引入一个联接型号。

    【讨论】:

    • 你可以使用多态,但是没有很好的方法用多态来做 FK 约束。如果 user1521444 还没有很好地掌握模型和关系,我会避免这样做。
    • 通过多态关联,您似乎可以让一个帐户属于用户或帐单,但同一个帐户是否可以在多态关联下同时属于两者?
    • 如果您可以同时拥有属于用户和计费者的帐户,我认为 AR 不支持开箱即用。你可以检查这个问题stackoverflow.com/questions/3209322/rails-polymorphic-has-many
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多