【问题标题】:Loading Relations加载关系
【发布时间】:2018-03-07 17:17:20
【问题描述】:

目标:我想将客户的所有医疗状况作为数组包含在客户的结果中。

为:

cust = Customer.includes(:conditions).find(1)

预期结果:

#<Customer id: 1, first_name: "John", last_name: "Doe", conditions [...]>

实际结果:

#<Customer id: 1, first_name: "John", last_name: "Doe">

代码

我有 2 个班级和第 3 个加入班级(ConditionsCustomer)。

class Customer < ApplicationRecord
    has_many :conditions_customers
    has_many :conditions, through: :conditions_customers
end

#join table. Contains 2 foreign_keys (customer_id, condition_id)
class ConditionsCustomer < ApplicationRecord
  belongs_to :customer
  belongs_to :condition
end

class Condition < ApplicationRecord
  has_many :conditions_customers
  has_many :customers, through: :conditions_customers
end

有趣的是,我看到 3 个选择查询被触发(客户、连接表和医疗条件表),所以我知道包含在一定程度上起作用,但不幸的是客户在没有医疗条件的情况下返回。

我也尝试过使用联接,但我一遍又一遍地得到一组相同的客户。

有没有一种简单的方法可以用 ActiveRecord 做到这一点?我宁愿不必手动合并记录。

【问题讨论】:

  • Customer.eager_load(:conditions).find(1)。这将在同一查询中加载连接的表。与.joins 不同,它使用左外连接,因此也会返回不匹配的行。 blog.bigbinary.com/2013/07/01/…
  • 您还应该注意,相关记录不包含在.inspect 的输出中。无论关联是否加载,您都会得到#&lt;Customer id: 1, first_name: "John", last_name: "Doe"&gt;。相反,如果你想调试它,你需要调用Customer.eager_load(:conditions).find(1).conditions.inspect
  • 谢谢,但在我的控制器中我会这样做:cust = Customer.eager_load(:conditions).find(params[:id]),然后是render json: cust and return。结果中仍然没有医疗状况..由我的邮递员工具验证
  • @JohnMarsh 您将cust 渲染为json ...但是您在哪里打电话给.conditions
  • as_json 默认情况下不包括关联。您必须明确告诉它包含关联。 render json: cust, include: [:conditions]

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


【解决方案1】:

通过活动记录实际上不可能,因为 json 提供了一些很酷的可能性:

render json: customers,
       include: {
         conditions: {
           only: [:attr1, :attr2], # filter returned fields
           methods: [:meth1, :meth2] # if you need model methods
         },
         another_joined_model: {
             except: [:password] # to exclude specific fields
         }
       }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-28
    • 2016-01-27
    • 1970-01-01
    • 2019-06-19
    • 2012-09-08
    • 2013-10-29
    • 2020-04-09
    相关资源
    最近更新 更多