order by foreign key in activerecord

本秂侑毒 提交于 2019-12-12 12:16:08

问题


I have a tables Foo and Bar. Foo has one Bar. When I query Foo, how can I order it by a date column in the Bar table?

Thanks


回答1:


Foo.find(:all,:joins=>:boo, :order=>'bars.created_at DESC' )



回答2:


Refer to the ActiveRecord Query Interface page: http://guides.rubyonrails.org/active_record_querying.html#joining-tables

Note that sometimes a prefix is added to the table name so you may need to do something like:

Foo.all(:joins => :bar, :order => Bar.table_name + '.created_at')


来源:https://stackoverflow.com/questions/1586848/order-by-foreign-key-in-activerecord

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!