【问题标题】:Rails 5 check if record exist in belongs_to relations?Rails 5检查belongs_to关系中是否存在记录?
【发布时间】:2019-03-09 05:22:41
【问题描述】:

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

Account 
belongs_to :plan

Plan
belongs_to :user

User
has_may :plans

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

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

【问题讨论】:

  • 数据库中的accounts表中没有user_id列。您必须首先获取属于一个帐户的所有计划,然后您必须检查这些计划是否具有您正在寻找的特定用户。请澄清你的问题。你也想在模型之间遍历,我建议在模型之间添加has_many 关系。如果您不熟悉该概念,我建议您查看以下内容:guides.rubyonrails.org/association_basics.html

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


【解决方案1】:

我会使用joins 加入数据库表,这会在SQL 中产生INNER JOIN,然后为有问题的user_id 添加条件:

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

了解joins in the Rails Guides

【讨论】:

    【解决方案2】:

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

    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 指南:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-07
      • 2023-03-22
      • 2013-05-16
      相关资源
      最近更新 更多