我正在映射2个模型:
User
Account
class Account
has_many :users
class User
has_one :account
用户表作为其中的account_id。
现在,在“帐户”模型上,我想创建一个“主要用户”,该帐户的帐户仅关闭1次。
用户表具有一个 bool(boolean) 标志:is_primary,如何为具有is_primary和account_id映射的用户在帐户端创建has_one。
因此,SQL看起来像:
SELECT * FROM users where account_id=123 and is_primary = 1
所以我想要:
用户有一个帐户。
一个帐户有许多用户,也有一个主要用户。
最佳答案
方法1-添加新的关联
添加一个带有has_one
lambda的where
关联。这使您可以在当前架构中工作。
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
关于ruby-on-rails - 同时具有 'has_one'和 'has_many'但有一些约束的Rails模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9365068/