Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to order by a related model in default scope? -- Rails 3.1

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?

like image 609
Jacob Avatar asked Dec 12 '11 08:12

Jacob


2 Answers

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

like image 71
Marek Příhoda Avatar answered Oct 21 '22 19:10

Marek Příhoda


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

like image 28
keymone Avatar answered Oct 21 '22 18:10

keymone