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?
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With