Tutorial :ActiveRecord association model


I am new to rails and read this guide to get all the info so far.

I have a simple scenario and want to make sure whether or not my associations will work fine.

Scenario: User logs in -> sets up many groups -> each group has many employees

User model:

class User < ActiveRecord::Base      has_many :groups  end  

Group model:

class Group < ActiveRecord::Base      belongs_to :user      has_many :employees  end  

Employee model:

class Employee < ActiveRecord::Base      has_many :groups      belongs_to :group  end  


  • Will this work for the scenario I mentioned?
  • I am confused about how to get all Employees under a User. What would be the code for that?
  • If I need typical CRUD for all these models then would would be in my Action? index/create/update/destroy? Can someone point me to a good guide on actions?


I also like the has_many through --

class User < ActiveRecord::Base      has_many :groups      has_many :employees, :through=>:groups  end  

Then you can go:

user = User.find(23)  user.employees.do_something  

Otherwise, you could loop through your groups and its employees (kinda ugly, but will work)

User.first.groups.each{|group| group.employees.each{|employee| puts employee.name}}  


You have it together, for the most part, but I think you need to look at has_and_belongs_to_many (which you will frequently see abbreviated as habtm.) Index, create, update, and destroy would be your CRUD list for Ruby on Rails. As for a good guide, I like Agile Web Development With Rails, by Dave Thomas. (When I'm picking up a new topic, I like books - electronic or otherwise.) It's available online through The Practical Programmers. The question about "what's a good guide" is pretty subjective, so caveat emptor.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »