ruby 如何在Rails中将对象添加到关联关系中?

mzsu5hc0  于 2022-11-04  发布在  Ruby
关注(0)|答案(3)|浏览(155)

在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

有没有简单的方法可以做到这一点?

t3irkdon

t3irkdon1#

一种解决方法:

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 v5.0.0.1中可用

5sxhfpxr

5sxhfpxr2#

你可以这样做

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)
6mw9ycah

6mw9ycah3#

为了避免额外的查询和在内存中保留数组,可以使用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

相关问题