同时具有“ has_one”和“ has_many”但有一些约束的Rails模型 [英] Rails model that has both 'has_one' and 'has_many' but with some constraints
问题描述
我正在映射2种模型:
User
Account
class Account
has_many :users
class User
has_one :account
用户表作为其中的account_id。
The user table as the account_id in it.
现在在Account模型中,我想创建一个主要用户,该用户的帐户只有1个关。
用户表中有一个布尔标志:is_primary,我如何为具有is_primary和account_id映射的用户在帐户端创建has_one。
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.
因此,SQL如下所示:
So the SQL would look like:
SELECT * FROM users where account_id=123 and is_primary = 1
所以我想要:
一个用户有一个帐户。
一个帐户有多个用户,并且也有一个主要用户。
A user has an account. An account has many users, and has a single primary user also.
推荐答案
方法1-添加新的关联
添加 has_one
关联,并在位置
lambda。这使您可以在当前架构下工作。
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
现在:
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')
方法2-添加关联方法
class Account
has_many :users do
def primary
where(:is_primary => true).first
end
end
end
现在:
account.users.primary # returns the primary account
这篇关于同时具有“ has_one”和“ has_many”但有一些约束的Rails模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!