首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在rails中将对象附加到关联关系中?

如何在rails中将对象附加到关联关系中?
EN

Stack Overflow用户
提问于 2022-10-19 19:56:26
回答 3查看 42关注 0票数 0

在rails 4.1应用程序中,我需要向"AssociationRelation“添加一个对象

代码语言:javascript
复制
  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

有什么简单的方法吗?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2022-10-19 21:16:54

解决这一问题的办法:

代码语言:javascript
复制
  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中获得。

票数 1
EN

Stack Overflow用户

发布于 2022-10-19 21:04:24

你可以这样做

代码语言:javascript
复制
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)
票数 1
EN

Stack Overflow用户

发布于 2022-10-19 22:38:46

为了避免额外的查询和将数组保存在内存中,可以使用or

如下所示:

代码语言:javascript
复制
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
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74131153

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档