如何在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
相关产品推荐
相关产品推荐

