ruby-on-railsmodeldefault-scope

Rails application trying to set default_scope of a model


In this application the model Resource_Estimations are done by Companies. I wish to have a default sort order for the Resource_Estimations of the Company name.

Company Model

class Company < ActiveRecord::Base
   include ActiveModel::ForbiddenAttributesProtection
   ...
   has_many :resource_estimations, dependent: :destroy
   ...
   validates :exchange_id, :name, :full_name, presence: true

Resource_Estimation model

class ResourceEstimation < ActiveRecord::Base
   include ActiveModel::ForbiddenAttributesProtection
   ...
   belongs_to :company
   ...
   validates :company_id, :drill_id, :resource_type_id, :date,
      :fill_to_spill,:p10, :p50, :p90, presence: true
   ...
   default_scope  { order(:company => :asc) }

The last statement (default_scope) in the Resource_Estimation model is what I am trying to change. I want the sort order to be company.name as opposed to the current sort order of company_id. Have tried a number of things but so far no luck. Any suggestions welcome- thanks Pierre


Solution

  • Try to join the company first:

    default_scope  { joins(:company).order('companies.name ASC') }