【问题标题】:How define named scoped with order on associations如何根据关联顺序定义命名范围
【发布时间】:2014-01-23 18:28:00
【问题描述】:

我有两个模型。

 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 

对我不起作用,如下所示。

   @sizes = Size.size_brand_asc  # giving error

我如何根据鞋子品牌对尺码进行排序

【问题讨论】:

    标签: ruby-on-rails named-scope


    【解决方案1】:

    您可以通过以下方式实现此目的:

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

    用法:

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

    在鞋类中:

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

    【讨论】:

      【解决方案2】:

      一行回答

      scope :size_brand_asc, ->{joins(:shoe) & Shoe.brand_asc}
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-01-02
        • 2012-02-26
        • 1970-01-01
        • 1970-01-01
        • 2010-11-06
        相关资源
        最近更新 更多