Rails 模型同时具有“has_one"和“has_many",但有一些限制 [英] Rails model that has both 'has_one' and 'has_many' but with some constraints
问题描述
我正在映射 2 个模型:
I am mapping 2 models:
User
Account
class Account
has_many :users
class User
has_one :account
user 表作为其中的 account_id.
The user table as the account_id in it.
现在在帐户模型上,我想创建一个主要用户",一个帐户只有 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
关联与一个 where
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
这篇关于Rails 模型同时具有“has_one"和“has_many",但有一些限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!