Rails模型既有’has_one’又有’has_many’但有一些约束
我正在映射2个模型:
User Account class Account has_many :users class User has_one :account
用户表作为其中的account_id。
现在在帐户模型上,我想创建一个帐户只有1个关闭的“主要用户”。 用户表有一个布尔标志:is_primary,如何在帐户端为具有is_primary和account_id映射的用户创建has_one。
所以SQL看起来像:
SELECT * FROM users where account_id=123 and is_primary = 1
所以我想:
用户拥有一个帐户。 帐户有许多用户,并且还有一个主要用户。
方法1 – 添加新关联
添加一个与lambda相关的has_one
关联。 这允许您在当前架构中工作。
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
将primary_user_id字段添加到Account并为primary_user添加’has_one’关联可能更简单:
class Account has_many :users has_one :primary_user, :class_name => "User" end class User has_one :account end
如果必须使用现有模式(使用:is_primary boolean标志),则可以添加如下范围:
class User has_one :account scope :primary, where(:is_primary => true) end
然后将范围链接到用户查找:
account = Account.find(1) primary_user = account.users.primary.first
- 像Twitter粉丝这样的关系/在ActiveRecord中跟随
- 如何测试carrierwave文件是否已更改?
- 为什么我会遇到僵局? 使用Thread,Queue和ActiveRecord。 Ruby 1.9.3,Rails 2.3.18
- 使用rails嵌套模型来创建*外部对象并同时*编辑*现有的嵌套对象?
- ActiveRecord ::带有急切加载的计算会进行多个数据库查询吗?
- 使用RVM使用sinatra app加载Active Record gem时出错
- 如何获得最高计数的关联模型(Rails)?
- 在has_many关联中为“no children”创建named_scope
- Rails 3连接 – 仅选择某些列