Question

I have two models.

 class Shoe < ActiveRecord::Base     
   has_many :sizes, :dependent => :destroy
   scope :brand_asc , order('brand ASC')  
   scope :brand_desc , order('brand DESC')
   attr_accessible :brand ,:model
 end


 class Size < ActiveRecord::Base
   belongs_to :shoe
   scope :size_brand_asc , order("#{self.shoe.brand} ASC")
   scope :size_brand_desc , order("#{self.shoe.brand} DESC")             
 end

It is very easy to call named scope on Shoe model like below.

  @shoes = Shoe.brand_asc

But i want to sort sizes on the base of "brand" that is attribute of shoe model.so this 

is not working for me like below.

   @sizes = Size.size_brand_asc  # giving error

How i can sort sizes on base of shoe brand

Was it helpful?

Solution

You can achieve this by doing like the following:

class Size < ActiveRecord::Base
  belongs_to :shoe
  scope :brand_ordered, lambda do |way = 'ASC'| 
    includes(:shoe).order("shoes.brand #{way}")
  end

Usage:

@sizes = Size.brand_ordered('DESC')
# or
@sizes = Size.brand_ordered('ASC')
# equivalent:
@sizes = Size.brand_ordered

In the Shoe class:

class Shoe < ActiveRecord::Base
  scope :brand_ordered, lambda do |way = 'ASC'| 
    order("#{self.table_name}.brand #{way}")
  end           

OTHER TIPS

one line answer

scope :size_brand_asc, ->{joins(:shoe) & Shoe.brand_asc}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top