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

我正在映射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')

方法2 – 添加关联方法

class Account 
  has_many :users do
    def primary
      where(:is_primary => true).first
    end
  end
end

现在:

account.users.primary # returns the primary account

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...