How can I write the following default scope:
class SimilarMerchant < ActiveRecord::Base
# relationships
belongs_to :merchant
belongs_to :similar_merchant, :foreign_key => 'similar_merchant_id', :class_name => "Merchant"
# scopes
default_scope order('merchants.is_paid DESC').order('score DESC')
end
Basically I want to sort by a merchant.is_paid
field (which belongs to a related model)
Any advice?
Try this:
default_scope joins(:merchant).order('merchants.is_paid DESC, score DESC')
And please bear in mind it can be slow, depending on the number of the records
here's what you could do to have required functionality but it's not great idea to do so, please read until the end
you can define your default scope to also include merchants association and then order by merchants.is_paid DESC, score DESC
would look something like
default_scope includes(:merchants).order('merchants.is_paid DESC, score DESC')
however that means every time you grab similar merchant objects for any reason you will have association loaded as well
this is not great and i would suggest to have a explicit scope for loading similar merchants with association and ordering:
scope :with_merchants, includes(:merchants).order(...)
that way you always know in your code what exactly is being loaded from database
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With