Rails model that has both 'has_one' and 'has_many' but with some constraints

后端 未结 2 1151
青春惊慌失措
青春惊慌失措 2020-12-13 05:04

I am mapping 2 models:

User
Account

class Account 
  has_many :users


class User
  has_one :account

The user table as the account_id in i

相关标签:
2条回答
  • 2020-12-13 05:31

    Approach 1 - Add a new association

    Add an has_one association with a where lambda. This allows you to work within your current schema.

    class Account 
      has_many :users
      has_one  :primary_user, -> { where(is_primary: true) }, :class_name=> "User"
    end
    

    Now:

    account.users #returns all users associated with the account
    account.primary_user #returns the primary user associated with the account
    # creates a user with is_primary set to true
    account.build_primary_user(name: 'foo bar', email: 'bar@foo.com')
    

    Approach 2 - Add an association method

    class Account 
      has_many :users do
        def primary
          where(:is_primary => true).first
        end
      end
    end
    

    Now:

    account.users.primary # returns the primary account
    
    0 讨论(0)
  • 2020-12-13 05:35

    It would probably be simpler to add a primary_user_id field to Account, and add a 'has_one' association for the primary_user:

    class Account
      has_many :users
      has_one :primary_user, :class_name => "User"
    end
    
    class User
      has_one :account
    end
    

    If you must use the existing schema (with the :is_primary boolean flag), you can add a scope like this:

    class User
      has_one :account
      scope :primary, where(:is_primary => true)
    end
    

    and then chain the scope to the users lookup:

    account = Account.find(1)
    primary_user = account.users.primary.first
    
    0 讨论(0)
提交回复
热议问题