How to manage n:n relationships with Rails?
-
18-09-2019 - |
Question
Let's say I have a Company
that has many Employees
and each Employee
can have many Companies
.
Basically I will have :
class Employee < ActiveRecord::Base
has_and_belongs_to_many :companies
end
and
class Company < ActiveRecord::Base
has_and_belongs_to_many :employees
end
But then I'm confused about how I could get things like:
- All the employees of a company with the name starting by "John"
- All the employees of a company order by name first, email second.
Is there some magic I don't know about? The example is just here for the demo, feel free to make assumptions or change it if it helps you explain better.
Solution
For getting all the employees starting with "John", you can do (of course there are many other ways to do it, but anyway):
some_company.employees.find(:all, :conditions => "name LIKE 'John%'")
For ordering of the employees it's even prettier:
class Company < ActiveRecord::Base
has_and_belongs_to_many :employees, :order => "name, email"
end
There are a whole lot more you can do with ActiveRecord. I suggest that you try reading up on http://guides.rubyonrails.org/ or watch http://railscasts.com/ to learn more about the beauty of RoR =)
Hope it helps!
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow