在 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
有沒有一種簡單的方法可以做到這一點?
uj5u.com熱心網友回復:
解決這個問題的一種方法:
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
uj5u.com熱心網友回復:
你可以這樣做
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)
uj5u.com熱心網友回復:
為了避免額外的查詢并將陣列保存在記憶體中,您可以使用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)
)
end
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/518610.html
