简体   繁体   English

ActiveRecord通过作用域从has_many和相关关系中获取记录

[英]ActiveRecord fetching records from has_many and related relationship through scopes

I have two models: Customer and Order . 我有两个模型: CustomerOrder Sometimes it happens that two Customers are actually the same customer, which is indicated by one of them having a master_id which points to another Customer record. 有时,两个客户实际上是同一位客户,这可能是由其中一个客户拥有一个master_id指向另一个客户记录来表示的。 When fetching Orders for a customer, I'd also like to fetch Orders from slave Customers (ie the ones that claim the Customer I'm querying from is their master Customer record). 在为客户获取订单时,我还想从从属客户那里获取订单(即那些声称要查询的客户的是其主客户记录)。

So: 所以:

Customer1: id: 1, master_id: nil, orders: [Order1, Order2]

Customer2: id: 2, master_id: 1, orders: [Order3]

query Customer1.all_orders should return all 3 Order objects 查询Customer1.all_orders应该返回所有3个Order对象

I know how to do this through a method - pluck ids of slave Customers, add the original customer's id to the array and then look for Orders whose customer_id is in this array: 我知道如何通过一种方法来执行此操作-抽取从属客户的ID,将原始客户的ID添加到数组中,然后查找其customer_id在此数组中的Orders:

has_many :slave_records, class_name: 'Customer', foreign_key: 'master_id'

def all_orders
  order_ids = slave_records.map(&:id).push(id)
  Order.where(customer_id: order_ids)
end

But is there a way to do this using scopes and relations? 但是有没有办法使用范围和关系来做到这一点? It's Rails 4 (I know that Rails 5 was supposed to have an OR thing in its version of ActiveRecord). 是Rails 4(我知道Rails 5应该在其ActiveRecord版本中具有OR东西)。

Adding scope in Order model will get you closer to what you want. 在Order模型中添加范围将使您更接近所需的范围。

class Order
  scope :for_master, -> (master) { where("customer_id = #{master.id} OR customer_id IN (?)", master.slave_records.select(:id)) }
end

So for any master customer, call the scope and you will get orders for children too. 因此,对于任何主要客户,调用示波器,您也将获得儿童订单。

Order.for_master(customer)

You will not be able to call customer.all_orders . 您将无法致电customer.all_orders But, you will be able to get all results in a cleaner way. 但是,您将能够以更简洁的方式获得所有结果。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM