Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
501 views
in Technique[技术] by (71.8m points)

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

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 it.

Now on the Account model I want to create a 'primary user' which an account only has 1 off. The user table has a boolean flag :is_primary, how can I create a has_one on the account side for a user who has the is_primary and account_id mapped.

So the SQL would look like:

SELECT * FROM users where account_id=123 and is_primary = 1

So I want:

A user has an account. An account has many users, and has a single primary user also.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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: '[email protected]')

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...