Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I order a has_many through association in Ruby on Rails?

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.

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' 

however this does not work.

How can I sort users by last_name when given a task?

like image 615
rswolff Avatar asked Feb 05 '10 07:02

rswolff


People also ask

How would you choose between Belongs_to and Has_one?

They essentially do the same thing, the only difference is what side of the relationship you are on. If a User has a Profile , then in the User class you'd have has_one :profile and in the Profile class you'd have belongs_to :user . To determine who "has" the other object, look at where the foreign key is.

What is polymorphic association in Rails?

In Ruby on Rails, a polymorphic association is an Active Record association that can connect a model to multiple other models. For example, we can use a single association to connect the Review model with the Event and Restaurant models, allowing us to connect a review with either an event or a restaurant.

What has and belongs to many or has many through?

Stories can belong to many categories. Categories can have many stories. has_many :through gives you a third model which can be used to store various other pieces of information which don't belong to either of the original models. Person can subscribe to many magazines.

What are associations in Ruby?

Association in Rails defines the relationship between models. It is also the connection between two Active Record models. To figure out the relationship between models, we have to determine the types of relationship. Whether it; belongs_to, has_many, has_one, has_one:through, has_and_belongs_to_many.


1 Answers

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 
like image 186
Daniel Avatar answered Oct 13 '22 03:10

Daniel