通过关联创建ActiveRecord has_one

时间:2017-06-10 22:38:58

标签: ruby-on-rails activerecord orm rails-activerecord ruby-on-rails-5

根据下面的ActiveRecord模型和关联,我需要在帐户模型上添加has_one :owner关联,以引用account_user角色设置为"所有者"的用户。

AccountUser模型具有角色属性

class AccountUser < ApplicationRecord
  enum role: [:user, :admin, :owner]

  belongs_to :account
  belongs_to :user
end

帐户模型通过帐户用户拥有许多用户。

class Account < ApplicationRecord
  has_many :account_users
  has_many :users, through: :account_users
  has_one  :owner, -> { where(role: :owner) } #, correct options here.
end

用户模型帐户用户拥有多个帐户

class User < ApplicationRecord
  has_many :account_users
  has_many :accounts, through: :account_users
end

1 个答案:

答案 0 :(得分:1)

尝试建立中间关联account_owner

class Account < ApplicationRecord
  has_many :account_users
  has_many :users, through: :account_users

  has_one :account_owner, -> { where(role: :owner) }, class_name: 'AccountUser'
  has_one :owner, through: :account_owner, source: :user
end