【问题标题】:Rails order collection by attribute of associated model?Rails按关联模型的属性收集订单?
【发布时间】:2011-09-11 06:50:33
【问题描述】:

我正在尝试找出一种方法来根据收集到的模型的关联属性来订购模型的集合(我认为......真是满嘴)。这就是我正在做的事情:

class Item < ActiveRecord::Base
  belongs_to :category
end

class Order < ActiveRecord::Base
  has_many :items, :order => :category_id
end

目前order.items 返回按 category_id 排序的项目。但我真正想要的是按字母顺序列出它们category.name。这可能吗?

谢谢, 斯图尔特

【问题讨论】:

    标签: ruby-on-rails collections associations ruby-on-rails-3.1


    【解决方案1】:

    如果您使用 :include 急切加载类别,它应该可以工作。

    class Order < ActiveRecord::Base
      has_many :items, :include => :categories, :order => "categories.name"
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多