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

问题描述 投票:0回答:2

我有3个模型帐户,计划和用户(我不能修改关系模型结构,但添加范围或方法)

Account 
belongs_to :plan

Plan
belongs_to :user

User
has_may :plans

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

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

ruby-on-rails ruby activerecord ruby-on-rails-5
2个回答
0
投票

我将使用joins加入数据库表,这会在SQL中生成INNER JOIN,而不是为user_id添加条件:

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

了解joins in the Rails Guides


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将自动处理计划表中的加入。

请参阅Rails指南:

© www.soinside.com 2019 - 2024. All rights reserved.