Joshua Azemoh
Joshua Azemoh

Reputation: 179

Create ActiveRecord has_one through association

Given the ActiveRecord models and associations below, I need to add a has_one :owner association on the account model to reference a user whose account_user role is set to "owner".

AccountUser model have a role attribute

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

  belongs_to :account
  belongs_to :user
end

Account Model Has many users through account users.

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

User Model Has many accounts through account users

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

Upvotes: 2

Views: 314

Answers (1)

Ilya Lavrov
Ilya Lavrov

Reputation: 2860

Try to make an intermediate association 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

Upvotes: 1

Related Questions