Rails的模型,有两个“HAS_ONE'和'的has_many”但也有一些约束上 [英] Rails model that has both 'has_one' and 'has_many' but with some contraints

查看:197
本文介绍了Rails的模型,有两个“HAS_ONE'和'的has_many”但也有一些约束上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我映射2款:

User
Account

class Account 
  has_many :users


class User
  has_one :account

用户表作为它的ACCOUNT_ID。

The user table as the account_id in it.

现在的客户模式,我想创建一个主要用户,这一个账户只有1了。 用户表中有一个布尔标志:is_primary,我怎么能创建的帐户侧谁拥有is_primary和ACCOUNT_ID映射用户的HAS_ONE

Now on the Account model I want to create a 'primary user' which an account only has 1 off. The user table has a boolean flag :is_primary, how can I create a has_one on the account side for a user who has the is_primary and account_id mapped.

所以SQL就像:

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

于是我想:

一个用户帐户。 一个帐户拥有众多用户,并拥有一个主要用户也。

A user has an account. An account has many users, and has a single primary user also.

推荐答案

方法1 - 添加一个新的关联

添加 HAS_ONE 协会与其中,拉姆达。这使您能够将当前架构内工作。

Add an has_one association with a where lambda. This allows you to work within your current schema.

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

这篇关于Rails的模型,有两个“HAS_ONE'和'的has_many”但也有一些约束上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆