Hi,
I’m planning a new application and after all I’ve read a RESTful rails
app
seems to be perfect for the job. But since a few days I’m struggling
with
routing… here’s my simple test. If would be great if someone could
enlighten me…
Three models: Person <----> Employment <----> Company
class Person < ActiveRecord::Base
has_many :employments
has_many :companies, :through => :employments
end
class Employment < ActiveRecord::Base
belongs_to :company
belongs_to :person
end
class Company < ActiveRecord::Base
has_many :employments
has_many :people, :through => :employments
end
I’ve created the models and generated all three controllers with the
scaffold_resource generator.
- I would like the following URLs to work correct:
http://localhost:3000/companies
http://localhost:3000/companies/2
http://localhost:3000/people
This is quite simple. I just added two routes:
map.resources :companies
map.resources :people
- Now I would like the following to work:
http://localhost:3000/companies/1/people
This should show me a list with all people assigned (via Employment) to
company with ID=1.
This route seem’s like a starting point:
map.resources :companies do |company|
company.resources :people
end
Now I think I must enhance the CompaniesController. Changing my
controller to
something like this…
def index
@companies = Person.find(params[:person_id]).companies
end
… seems to work, but of course http://localhost:3000/companies stopped
working.
Do I really have to change my index method again to decide between
“person_id
is set, look for Person.find(:person_id).companies” and “no person_id,
so do
a Company.find(:all)”?
What happens when my application is growing and there are many models
connected with my Person-model? Isn’t there some of this
rails-magic-glue
that’s doing the dirty work?
I also thought that calling something like
http://localhost/companies/42/people/new would automagically create the
association between the Company with ID 42 and the newly entered
Person…?
Regards,
Timo