简体   繁体   English

如何通过多属性获取唯一记录

[英]How to get unique record by multi-attributes

I have a model like this: Order(id: integer, user_id: integer, target_id: integer, content: string, created_at: datetime, updated_at: datetime) 我有一个这样的模型:Order(id:整数,user_id:整数,target_id:整数,内容:字符串,created_at:日期时间,Updated_at:日期时间)

It belongs to User. 它属于User。 User can make order for each other like: 用户可以像这样相互订购:

  • person A -> person B 人A->人B
  • person B -> person A 人B->人A
  • person A -> person B 人A->人B

=> The unique record should be A -> B, so how can I filter Order to unique record ? =>唯一记录应为A-> B,那么如何将Order过滤为唯一记录?

Okay, assuming you have users A and B, you should just be able to do this: 好的,假设您有用户A和B,则应该能够执行以下操作:

Order.where(user: A, target: B)

...assuming you've defined your associations, otherwise: ...假设您已经定义了关联,否则:

Order.where(user_id: A.id, target_id: B.id)

EDIT: just saw your comment. 编辑:刚刚看到您的评论。 You could add .first to either of the above queries just to get the first order if you wanted to. 您可以将.first添加到上述任一查询中,以获取第一订单。

ANOTHER EDIT: As I understand it, if there's ever been one or more orders between A and B (or B and A), you want to grab one of them, and you don't care which. 另一个编辑:据我了解,如果A和B(或B和A)之间曾经有一个或多个订单,那么您想抓住其中一个,而不必在意。 You could do this: 您可以这样做:

(Order.where(user: A, target: B) + Order.where(user: B, target: A)).first

That will give you a record if one exists and nil if it doesn't. 如果有一个记录,它将为您提供一条记录,如果不存在,则nil Raw SQL would be more efficient: 原始SQL将更有效:

Order.where("user_id = ? AND target_id = ? OR user_id = ? AND target_id = ?", A.id, B.id, B.id, A.id).first

... but less readable, and be sure to test it. ...但是可读性较差,请务必对其进行测试。 Good luck! 祝好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Ruby on Rails —验证唯一记录,而不仅仅是记录的唯一属性 - Ruby on Rails — validating a unique record, not just unique attributes of a record ActiveRecord如何获取集合中所有唯一的属具属性? - Activerecord how to get all unique belongs_to attributes in a set? 如何获得具有一定数量属性(取决于记录)的记录? - How to get a records that have a a certain number of attributes, dependent on the record? 如何获取rails活动记录属性对应的SQL值 - How to get rails active record attributes corresponding SQL values 如何通过Rails的where方法通过特殊列获取唯一记录? - How to get unique record by special column from a where method with Rails? 如何在多记录Rails表单中为复选框设置唯一ID? - How do I set a unique ID for checkboxes in a multi-record Rails form? 如何基于列从Active Record导轨4获取唯一记录 - How to get unique records from Active Record rails 4 based on a column 获取活动记录中每个属性的唯一记录 - Get Unique records per attribute in Active Record 如何在Rails 4中向活动记录添加属性? - How to add attributes to a active record result in Rails 4? 如何在Active Record模型上存储临时属性 - how to store temporary attributes on an Active Record model
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM