Rails 5检查记录是否存在于belongs_to关系中?

时间:2019-03-09 05:22:41

标签: ruby-on-rails ruby activerecord ruby-on-rails-5

我有3个模型Account,Plan和User(并且我不能修改关系模型结构,但可以添加范围或方法)

Account 
belongs_to :plan

Plan
belongs_to :user

User
has_may :plans

我想知道是否存在一个具有特定user_id的帐户

Account.exists?…….. //这是我的问题

2 个答案:

答案 0 :(得分:0)

我将使用joins联接数据库表,这将导致在SQL中产生INNER JOIN,然后为所讨论的user_id添加条件:

Account.joins(plan: :user).where(users: { id: user_id }).exists?

了解joins in the Rails Guides

答案 1 :(得分:0)

您可以创建通过计划模型链接帐户和用户的间接关联:

class Account < ApplicationRecord
  belongs_to :plan
  has_one :user, through: :plan
end

class Plan < ApplicationRecord
  belongs_to :user
end

class User < ApplicationRecord
  has_may :plans
  has_many :accounts, through: :plans
end

这将使您查询:

Account.joins(:user)
       .where(users: { id: user_id })
       .exists?

ActiveRecord将自动处理通过plans表进行的联接。

请参阅Rails指南: