Rails中使用joins关联Customer与Account表,无法获取Account字段求助
解决ActiveRecord关联查询无法获取关联表字段的问题
嘿,我懂你的困扰——你已经通过joins关联了Customer和Account表,并且指定要查询Account的opening_balance字段,但返回的Customer实例里就是看不到这个值,对吧?这其实是ActiveRecord的默认行为导致的,我来给你解释原因和解决办法:
问题原因
你查询返回的是Customer::ActiveRecord_Relation集合,每个元素都是Customer模型的实例。ActiveRecord只会自动把查询结果中属于Customer模型数据库字段的值赋值给这些实例,而关联表(Account)的字段不会自动映射到Customer实例的属性里,哪怕你在select里指定了它们。
解决方案
这里有几种常用的解决方式,你可以根据需求选择:
1. 给关联字段起别名 + 定义attr_accessor
这是最常用的方法,让Customer实例能够访问这个额外的字段:
- 首先在Customer模型里添加一个attr_accessor,用来存储关联字段的值:
# app/models/customer.rb class Customer < ApplicationRecord has_one :account attr_accessor :opening_balance # 添加这个属性访问器 end - 然后在查询的时候给
accounts.opening_balance起一个和attr_accessor同名的别名:
现在你就可以通过Customer.joins(:account).select("customers.id, customers.name, accounts.opening_balance AS opening_balance")customer.opening_balance获取到对应的账户余额了。
2. 使用pluck直接获取数组数据
如果你不需要ActiveRecord对象,只是想要纯数据的话,可以用pluck,它会直接返回包含字段值的二维数组:
Customer.joins(:account).pluck("customers.id", "customers.name", "accounts.opening_balance")
返回结果类似:
[[1774, "James TEA", 2000], [1777, "Joseph STORE", 5000], ...]
3. 使用select_all获取原始哈希记录
如果你想保留字段名和值的对应关系,又不想修改模型,可以用select_all获取原始的数据库查询结果(哈希数组):
results = Customer.connection.select_all( Customer.joins(:account).select("customers.id, customers.name, accounts.opening_balance").to_sql )
返回的结果是一个数组,每个元素是包含所有查询字段的哈希:
[ {"id"=>1774, "name"=>"James TEA", "opening_balance"=>2000}, {"id"=>1777, "name"=>"Joseph STORE", "opening_balance"=>5000}, ... ]
4. 定义可复用的Scope
如果这个查询是你经常需要用到的,可以在Customer模型里定义一个scope,把查询逻辑封装起来:
# app/models/customer.rb class Customer < ApplicationRecord has_one :account attr_accessor :opening_balance scope :with_account_balance, -> { joins(:account).select("customers.id, customers.name, accounts.opening_balance AS opening_balance") } end
之后你就可以直接调用Customer.with_account_balance来获取包含账户余额的Customer实例集合了。
内容的提问来源于stack exchange,提问作者Umesh Malhotra
相关产品推荐
相关产品推荐

