开发者

Rails 3 default_scope sort by foreign key object name?

开发者 https://www.devze.com 2023-03-09 18:52 出处:网络
I\'m having a little trouble figuring this out: I have a model Machine that has a foreign key on a locations table, and I want the default scope of Machine to sort by location.name开发者_JAVA技巧. Is

I'm having a little trouble figuring this out: I have a model Machine that has a foreign key on a locations table, and I want the default scope of Machine to sort by location.name开发者_JAVA技巧. Is this possible?


Yes, use a join to your other table.

class Machine < ActiveRecord::Base

  default_scope joins(:location).order('locations.name')

end

Make sure the relation you call in joins matches the one defined in your Machine model.


Yes, in your Machine model:

has_many :locations, :order => "name ASC"
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号