[英]Rails. Active Record. Odrer by associated table columns
假设我的网站有三个表:
class Group < ActiveRecord::Base
has_many :items
end
class Item < ActiveRecord::Base
has_many :urls
belongs_to :group, touch: true
end
class Url < ActiveRecord::Base
belongs_to :item
end
因此,我需要获取在group1中按其项名称排序的Ulrs列表。
类似的问题是如何获取Urls的完整列表(按其组名,然后按项目名排序)。
用sort_by方法创建几个简单的循环不是问题,但如果没有它们,也许有任何优雅的方法可以做到这一点? 似乎.where和.order方法不支持关联。
Url.joins(item: :group).
where(groups: {name: 'group1'}).
order('groups.name ASC, items.name ASC')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.