开发者

Rails 3: Order a query that uses a has_many and belongs_to association in one query

In my Rails db 开发者_如何学JAVAscheme there is the following structure:

tasks has many jobs jobs belongs to one category

What I want to achieve is to load all tasks with all the associated jobs ordered by their category. So the result should look something like this:

task1 job1 -> category1 job3 -> category2 job2 -> category3

task3 job5 -> category1 job9 -> category2 job4 -> category3

Note: the ordering of the categories is not their ID, it is a column.

Right now the only working solution is to order the jobs in Ruby and not SQL, which is pretty bad. I just stumpled on the :finder_sql option in the has_many association, but I am not sure if that's the way to go.


This would generate the correct sql, but Im not sure ActiveRecord wil preserve the order in the association:

Task.find(:all, :include => {:job => :category }, :order =>'tasks.id, categories.column')

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜