如何订购 Rails 3 中包含的元素
我有一个模型关系,其中 today
有许多 tasks
我正在尝试检索用户的 today
对象,包括 tasks
code> 并将它们全部渲染为 Json。所有这一切都进展顺利,直到我决定在 today
对象中订购 tasks
,因为 respond_with block
也用于渲染 html页。有什么方法可以包含任务
并对其进行排序吗?
我正在尝试这样的事情:
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解决这个问题的方法。
I have a model relationship where today
has many tasks
I'm trying to retrieve a user's today
object, include the tasks
and render them all to Json. All of this was going great until I decided I wanted to order the tasks
within the today
object because respond_with block
is also used for rendering the html page. Is there any way to include the tasks
and order them?
I'm trying something like this:
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
This retrieves everything correctly, but does not seem to order the tasks at all.
This is what I used to have (which worked great, but didn't have the ordering):
class TodaysController < ApplicationController
respond_to :html, :json
def show
@today = current_user.today
respond_with @today, :include => :tasks
end
end
I know I can retrieve the data and sort it afterwards like this:
@today = current_user.today
@today.tasks.sort!{|a,b| a.priority <=> b.priority }
This works and will pass my tests, but I was hoping for an ActiveRecord way to solve this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在您的
Today
模型中尝试一下:编辑:正如下面的评论中所述,在 Rails 4+ 中,现在是:
(更多信息)
Try this in your
Today
model:EDIT: As mentioned in comment below, in Rails 4+, this is now:
(more info here)
直接的解决方案是在优先级之前包含任务表名称:
或者,如果您不想对表名称进行硬编码,可以与范围合并>Task 模型:
此外,您可以将
has_many: Todays
添加到User
模型中,以放弃where
子句并执行以下操作 :您只需要/始终按优先级排序,不需要其他不同的排序,将
order
添加到has_many :tasks
更容易。Direct solution would be to include the
tasks
table name beforepriority
:Or, if you don't want to have the table name hardcoded, you can merge with scope from
Task
model:Also, you can add
has_many: todays
toUser
model to ditch thewhere
clause and do:But if you need only/always to order by priority, and do not need other different orderings, adding
order
tohas_many :tasks
is easier.