【问题标题】:Create ActiveRecord has_one through association通过关联创建 ActiveRecord has_one
【发布时间】:2017-11-12 16:58:46
【问题描述】:

鉴于下面的 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

【问题讨论】:

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


    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多