문제

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

도움이 되었습니까?

해결책

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           

다른 팁

one line answer

scope :size_brand_asc, ->{joins(:shoe) & Shoe.brand_asc}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top