ActiveRecord sort_by模型的关联

时间:2015-03-17 06:43:01

标签: ruby-on-rails sorting activerecord

我想使用where子句检索所有正确的ItemAttributes,然后按静态列order排序。

关系:

class ItemAttribute < ActiveRecord::Base
  belongs_to :static, primary_key:"name", foreign_key:"name"
end

class Static < ActiveRecord::Base
  has_many :item_attributes, :foreign_key => 'name', :primary_key => 'name'
end

没有完全做到的代码......

      @items = ItemAttribute.where(level:5)
      @sorted = @items.sort_by(&:static.order)

2 个答案:

答案 0 :(得分:2)

我喜欢使用范围并在其类中保留每个类的细节,对于类似这样的东西,我可以将范围添加到Static模型,

class Static < ActiveRecord::Base
  scope :sort_by_order, -> { order(order: :desc) } # or asc if you want
end

然后在查询中使用该范围

@sorted_items = ItemAttribute.joins(:static).where(level: 5).merge(Static.sort_by_order)

答案 1 :(得分:0)

@sorted_items = ItemAttribute.include(:static).where(level:5).order('statics.order')