ruby-on-rails - 同时具有 'has_one'和 'has_many'但有一些约束的Rails模型

标签 ruby-on-rails activerecord

我正在映射2个模型:

User
Account

class Account 
  has_many :users


class User
  has_one :account

用户表作为其中的account_id。

现在,在“帐户”模型上,我想创建一个“主要用户”,该帐户的帐户仅关闭1次。
用户表具有一个 bool(boolean) 标志:is_primary,如何为具有is_primary和account_id映射的用户在帐户端创建has_one。

因此,SQL看起来像:
SELECT * FROM users where account_id=123 and is_primary = 1

所以我想要:

用户有一个帐户。
一个帐户有许多用户,也有一个主要用户。

最佳答案

方法1-添加新的关联

添加一个带有has_one lambda的where关联。这使您可以在当前架构中工作。

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

关于ruby-on-rails - 同时具有 'has_one'和 'has_many'但有一些约束的Rails模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9365068/

相关文章:

ruby-on-rails - 我应该将 .Includes() 方法放在 .find() 之前还是之后?

ruby-on-rails - 使用named_scope的加性链接

ruby-on-rails - 我可以在没有开始...结束的情况下将重试放在救援 block 中吗?

ruby-on-rails - 更改设计消息 "Email has already been taken"

ruby-on-rails - 注册#create 中发生 ActiveRecord::RecordNotUnique 为什么?

ruby-on-rails - 动态路由 rails

ruby-on-rails - 为什么使用 Sidekiq 的 redis 命名空间不起作用?

php - Codeigniter:将 activeRecord 与手动查询相结合?

ruby-on-rails-3 - 如何配置 Active admin 支持 mongoid 和 active record?

sql - Find_by_sql作为Rails范围