【发布时间】:2011-07-17 21:56:39
【问题描述】:
我有一个模型关系,其中today 有很多tasks
我正在尝试检索用户的 today 对象,包括 tasks 并将它们全部呈现给 Json。所有这一切都很顺利,直到我决定在today 对象中订购tasks,因为respond_with block 也用于呈现html 页面。有什么方法可以包含tasks 并订购它们?
我正在尝试这样的事情:
class TodaysController < ApplicationController
respond_to :html, :json
def show
@today = Today.where(:user_id => current_user.id).joins(:tasks).includes(:tasks).order(:priority).first
respond_with @today, :include => :tasks
end
end
这会正确检索所有内容,但似乎根本没有对任务进行排序。
这是我曾经拥有的(效果很好,但没有订购):
class TodaysController < ApplicationController
respond_to :html, :json
def show
@today = current_user.today
respond_with @today, :include => :tasks
end
end
我知道我可以像这样检索数据并在之后对其进行排序:
@today = current_user.today
@today.tasks.sort!{|a,b| a.priority <=> b.priority }
这可行并且会通过我的测试,但我希望有一种 ActiveRecord 方法来解决这个问题。
【问题讨论】:
-
关于你的最后一行代码。下面稍微清楚一点:
@today.tasks.sort_by(&:priority).
标签: ruby-on-rails ruby activerecord arel