I have two models: Customer
and Order
. 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. 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
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:
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).
Adding scope in Order model will get you closer to what you want.
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
. But, you will be able to get all results in a cleaner way.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.