我正在映射2个模型:
- User
- Account
- class Account
- has_many :users
- class User
- has_one :account
用户表中的account_id在其中.
现在在帐户模型上,我想创建一个“主要用户”,一个帐户只有一个关闭.
用户表具有布尔标志:is_primary,如何为具有is_primary和account_id映射的用户在帐户端创建一个has_one.
所以sql将如下所示:
- SELECT * FROM users where account_id=123 and is_primary = 1
所以我想要
解决方法
方法1 – 添加新关联
添加一个has_one关联到一个lambda.这允许您在当前架构中工作.
- 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')
- class Account
- has_many :users do
- def primary
- where(:is_primary => true).first
- end
- end
- end
现在:
- account.users.primary # returns the primary account