Question:
company_user belongs to user, and belongs to company. Then, document
belongs to company.
I want to take a user, and grab all of the companies he belongs to, and
also grab all of the documents of those companies.
So I want to take user_id, grab the corrosponding company_users, then
from there use the company_users’ company_id to grab the companies,
then from there use the company_id in documents to match up with those
companies and grab them.
class Company < ActiveRecord::Base
has_and_belongs_to_many :users
…
end
class User < ActiveRecord::Base
has_and_belongs_to_many :companies
…
end
user = User.find(params[:id]) # assuming a request
companies = user.companies
user_documents = {}
companies.each { |company|
user_documents[company.name] = company.documents # use whatever key
is convenient for you
}
errr no… don’t get rid of the company_user table. You need it.
has_and_belongs_to_many is used for pure join tables where it contains
just
two foreign keys
has_many :through is for join tables that contain additional data, i.e.
it’s
intended to be used as another full-fledged model
Don’t think in terms of SQL anymore. Let rails handle it. The
associations
are what let rails automagically generate the SQL statements for you.
If
you tail -f your development.log you’ll see.
Brian, would you suggest I get rid of the company_users table? What
fields would I need to add to companies and users?
You need the table. What you might not need to do is explicitly
define the model. That’s the main difference between Brian’s code and
the code I posted. If companies_users stores only the appropriate
foreign keys, then use Brian’s method. If you need to store more info
for a user-company relationship, then my way will work.
– James
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.