我有一个模型关系,其中今天
有很多任务
我正在尝试检索用户的 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
模型中试试这个:
has_many :tasks, :order => 'priority DESC'
编辑:正如下面评论中提到的,在 Rails 4+ 中,现在是:
has_many :tasks, -> { order(:priority => :desc) }
( more info here )
关于ruby-on-rails - 如何在 Rails 3 中订购包含的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5348116/