I am a newbie to the Ruby on Rails but stuck at this interesting situation :
I have three Models with me :
- User
- Company
- Project
I want to relate them in the following way :
- Company has_many Users
-
Users belong_to Company
Implemented via company_id column in USERS table
User.CompanyorCompany.Usersworks fine.
- Project has_and_belongs_to_many Users
-
Users has_and_belongs_to_many Project
Implemented via has_and_belongs_to_many relation using in projetcs_users table
Project.UsersorUser.Projectsworks fine.
The real problem comes when I want them to join as following as well :
- Company belong_to Owners (:through => User)
-
Owner has_one Company
—A company can have multiple owners but one user can own just one company. He can’t be owner of multiple companies.
—A user may or may not be owner of a company but always belong to some company.
—A user cannot be part of two companies. -
Project has_one Project_manager (:through => User)
-
Project_manager belongs_to Projects
—A Project can have just one Project_manager but one can be project manager of multiple projects.
I am not able to figure out how the relationship should be defined in the Models. Also what should be the table structure for all three models.
My objective is to achieve :
-
Company.Owners
It can be done by :
@owner = User.find(Company.owner_id) -
Project.Project_manager
It can be done by :
@Project_manager = User.find(Project.project_manager_id)
But don’t want it that way to work !!
Rest is working perfectly fine for me.
This should help you get on the right track:
Rails ActiveRecord relations are very well documented. See the documentation http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html