ruby-on-rails – 具有’has_one’和’has_many’但具有某些约束的Rails模型

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – 具有’has_one’和’has_many’但具有某些约束的Rails模型前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在映射2个模型:
  1. User
  2. Account
  3.  
  4. class Account
  5. has_many :users
  6.  
  7.  
  8. class User
  9. has_one :account

用户表中的account_id在其中.

现在在帐户模型上,我想创建一个“主要用户”,一个帐户只有一个关闭.
用户表具有布尔标志:is_primary,如何为具有is_primary和account_id映射的用户在帐户端创建一个has_one.

所以sql将如下所示:

  1. SELECT * FROM users where account_id=123 and is_primary = 1

所以我想要

用户有一个帐户.
一个帐户有很多用户,也有一个主要用户.

解决方法

方法1 – 添加新关联

添加一个has_one关联到一个lambda.这允许您在当前架构中工作.

  1. class Account
  2. has_many :users
  3. has_one :primary_user,-> { where(is_primary: true) },:class_name=> "User"
  4. end

现在:

  1. account.users #returns all users associated with the account
  2. account.primary_user #returns the primary user associated with the account
  3. # creates a user with is_primary set to true
  4. account.build_primary_user(name: 'foo bar',email: 'bar@foo.com')

方法2 – 添加关联方法

  1. class Account
  2. has_many :users do
  3. def primary
  4. where(:is_primary => true).first
  5. end
  6. end
  7. end

现在:

  1. account.users.primary # returns the primary account

猜你在找的Ruby相关文章