我有3个模型帐户,计划和用户(我不能修改关系模型结构,但添加范围或方法)
Account
belongs_to :plan
Plan
belongs_to :user
User
has_may :plans
我想知道是否存在具有特定user_id的帐户
Account.exists?...... .. //这是我的问题
我将使用joins
加入数据库表,这会在SQL中生成INNER JOIN
,而不是为user_id
添加条件:
Account.joins(plan: :user).where(users: { id: user_id }).exists?
您可以创建通过计划模型链接帐户和用户的间接关联:
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指南: