在rails 4.1应用程序中,我需要向"AssociationRelation“添加一个对象
def index
employee = Employee.where(id_person: params[:id_person]).take
receipts_t = employee.receipts.where(:consent => true) #gives 3 results
receipts_n = employee.receipts.where(:consent => nil).limit(1) #gives 1 result
#I would need to add the null consent query result to the true consent results
#something similar to this and the result is still an association relation
@receipts = receipts_t + receipts_n
end有什么简单的方法吗?
发布于 2022-10-19 21:16:54
解决这一问题的办法:
def index
employee_receipts = Employee.find_by(id_person: params[:id_person]).receipts
receipts_t = employee_receipts.where(consent: true)
receipts_n = employee_receipts.where(consent: nil).limit(1)
@receipts = Receipt.where(id: receipts_t.ids + receipts_n.ids)
end不幸的是,这里不能使用.or(),因为它只能从Rails版本5.0.0.1中获得。
发布于 2022-10-19 21:04:24
你可以这样做
receipts_t_ids = employee.receipts.where(:consent => true).pluck(:id)
receipts_n_ids = employee.receipts.where(:consent => nil).limit(1).pluck(:id)
@receipts = Receipt.where(id: receipts_t_ids + receipts_n_ids)发布于 2022-10-19 22:38:46
为了避免额外的查询和将数组保存在内存中,可以使用or
如下所示:
def index
employee_receipts = Employee.find_by(id_person: params[:id_person]).receipts
@receipts =
employee_receipts.where(consent: true).or(
employee_receipts.where(consent: nil).limit(1)
)
endhttps://stackoverflow.com/questions/74131153
复制相似问题