0

I have a database with tables Exchanges, Company, and Company_Listings.

Exchanges table
  name
  full_name

Companies table
  name
  full_name
  exchange_id

Company_Listings table
  company_id
  exchange_id
  company_code
  option_name
  [...] other columns

If the listing is a company it will have a company_code e.g. BHP and if it is a company option it will have a option_name e.g. BHPXX but no company_code. Both with link via company_id to the company "Broken Hill Billiton Pty Ltd."

Exchanges model
  has_many :companies, dependent: :destroy
  has_many :company_listings, dependent: :destroy 

Companies Model 
  belongs_to :exchange
  has_many :company_listings,

Company_Listing Model
  belongs_to :company
  belongs_to :exchange
  default_scope { order('exchange_id ASC', 'company_code ASC', 'option_name ASC') }

The default scope orders company listings as BHP, CBA ... BHPXX.

I am trying to get the sort so that it gives BHP, BHPXX, CBA. Any help gratefully received.

Burak Erdem
  • 19,630
  • 7
  • 36
  • 56
user1854802
  • 388
  • 3
  • 14

1 Answers1

0

Try this:

default_scope { order('company_code ASC', 'option_name ASC', 'exchange_id ASC')

If that doesn't work because of the nulls, you may need to look at how it's done here:

ORDER BY ASC with Nulls at the Bottom

MySQL Orderby a number, Nulls last

default_scope { order('-company_code DESC', '-option_name DESC', 'exchange_id ASC')

EDIT: the above may not work here given that company_code and option_name are not numeric in nature, but the links provide plenty of other ways to do this.

Community
  • 1
  • 1
tirdadc
  • 4,603
  • 3
  • 38
  • 45