You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Rails 4.1中向AssociationRelation追加对象并保持关联类型?

解决方案

直接用+会把两个AssociationRelation转换成数组,无法保留ActiveRecord关系对象的链式调用等特性。要实现需求且结果仍为AssociationRelation,可以通过合并SQL查询条件的方式完成:

方法一:先获取目标记录ID再合并查询

def index
  employee = Employee.where(id_person: params[:id_person]).take
  # 拿到consent为nil的第一条记录ID
  nil_receipt_id = employee.receipts.where(consent: nil).limit(1).pluck(:id).first

  # 合并查询条件:consent为true 或是目标nil记录的ID
  @receipts = employee.receipts.where("consent = ? OR id = ?", true, nil_receipt_id)
end

方法二:使用子查询合并条件

def index
  employee = Employee.where(id_person: params[:id_person]).take
  # 通过子查询指定要包含的consent为nil的第一条记录
  @receipts = employee.receipts.where(
    "consent = ? OR id IN (SELECT id FROM receipts WHERE employee_id = ? AND consent IS NULL LIMIT 1)",
    true, employee.id
  )
end

注:Rails 4.1尚未引入ActiveRecord原生的or方法(该特性在Rails 5中添加),因此需要通过字符串形式编写SQL OR条件来合并查询。

内容的提问来源于stack exchange,提问作者Lucho

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 17:01:10