【发布时间】: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的输出中。无论关联是否加载,您都会得到#<Customer id: 1, first_name: "John", last_name: "Doe">。相反,如果你想调试它,你需要调用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