本文介绍了如何在Ruby on Rails中通过关联订购has_many?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
考虑到以下AR模型,当给定任务的句柄时,我想按姓氏字母对用户进行排序:
Given the following AR models, I would like to sort users alphabetically by last name when given a handle to a task:
#user
has_many :assignments
has_many :tasks, :through => :assignments
#assignment
belongs_to :task
belongs_to :user
#task
has_many :assignments
has_many :users, :through => :assignments
我想获得一个任务,然后导航到其分配的用户,并按字母顺序对用户列表进行排序.
I would like to get a task then navigation to its assigned users, and sort the user list alphabetically.
我一直认为我应该能够像这样将:order
子句添加到has_many :users, :through => :assignments
:
I keep thinking that I should be able to add the :order
clause to has_many :users, :through => :assignments
like this:
#task.rb
has_many :assignments
has_many :users, :through => :assignments, :order => 'last_name, first_name'
但是这不起作用.
给定任务后,如何按last_name
对用户进行排序?
How can I sort users by last_name
when given a task?
推荐答案
由于Rails 4中不推荐使用条件参数,因此应使用范围块:
Since condition arguments are deprecated in Rails 4, one should use scope blocks:
has_many :users, -> { order 'users.last_name, users.first_name' }, :through => :assignments
这篇关于如何在Ruby on Rails中通过关联订购has_many?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!