加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 20:42:42 所属栏目:百科 来源:网络整理
导读:我正在映射2个模型: UserAccountclass Account has_many :usersclass User has_one :account 用户表中的account_id在其中. 现在在帐户模型上,我想创建一个“主要用户”,一个帐户只有一个关闭. 用户表具有布尔标志:is_primary,如何为具有is_primary和accoun
我正在映射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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读