开发者

Rails 3 default_scope sort by foreign key object name?

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜