微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

原文地址:https://www.jb51.cc/ruby/273944.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐