Hi! I’m modeling my application and i have a question about
relationships:
I have 3 classes (tables): User (users), Company (companies) and Rol
(rols)
The relationship between the 3 classes is another table that has:
Joining table X
user_id
company_id
rol_id
Because a the same user can be in many companies. A company can have
many users. An a user have a single rol in a company but different
rols in another company.
So i can’t name my table like users_companies because i have another
field, the rol_id so i should find another name, lets say X.
My model should be something like?:
class User < ActiveRecord::Base
has_many :X
has_many :companies, :through => X
end
class Company < ActiveRecord::Base
has_many :X
has_many :users, :through => X
end
class X < ActiveRecord::Base
belongs_to :company
belongs_to :users
has_one :rol
end
And rol isn’t a class because just have the type of user (“Admin”,
“Regular”).
Is this ok? Is my first time doing this kind of relationship
Thanks in advance!
let me first clear something up:
is “rols” (yopu mean “roles”?) a real table? you wrote so. then why
shouldn’t it have a model-class? it should!
now about the association:
#tables:
users
companies
roles
jobs
class User < ActiveRecord::Base
has_many :jobs
has_many :companies, :through => :jobs
has_many :roles, through => :jobs
end
class Company < ActiveRecord::Base
has_many :jobs
has_many :users, :through => :jobs
has_many :companies, :though => :jobs
end
class Role < ActiveRecord::Base
has_many :jobs
has_many :users, :through => :jobs
has_many :companies, :through => :jobs
end
You can remove some of the associations when you don’t need them (e.g.
i dont see a use to find all companies that have a role “Admin”)
you can then do:
#controller
@user = User.find_by_id(1)
@jobs = @user.jobs.find :all, :include => :companies, :roles
#view
<% @jobs.each do |job| %>
Jobs of <%= @user.name %>
Company: <%= job.company.name %>
Role:<%= job.role.name %>
<% end %>
etc. pp.
On 6/1/07, Thorsten [email protected] wrote:
let me first clear something up:
is “rols” (yopu mean “roles”?) a real table? you wrote so. then why
shouldn’t it have a model-class? it should!
Yes, i realized that after sending the email.
has_many :companies, :through => :jobs
has_many :users, :through => :jobs
has_many :companies, :through => :jobs
end
I did something like that: classes: Role, User, Company and Profile (or
job).
Where Profile belongs_to user, company and role.
And User and Company have relationships like the one you wrote.
Jobs of <%= @user.name %>
Company: <%= job.company.name %>
Role:<%= job.role.name %>
<% end %>
etc. pp.
Thank you very much for your time and helping me understand this a bit
more.