问题
my models are:
class City < ActiveRecord::Base
belongs_to :region
has_many :activities
has_many :restaurants
end
class Activity < ActiveRecord::Base
belongs_to :city
end
I want acces all activities from all the cities. From a previous question on stackoverflow, i read that i can't do this @cities.activities, instead i did the following:
add has_many through association to Region
class Region < ActiveRecord::Base
has_many :activities, :through => :cities
end
@activities = @region.activities.find_all_by_homepage_city(true)
But when i call the variable @activities use the polymorphic_path.
- @activities.each do |b|
%li
=link_to b.name, polymorphic_path([@region, @city, b])
I get the message "not method for region_activity_path" . This is correct because there is no resources: activities after the resources: regions
resources :regions do
resources :cities do
resources :activities
I can add activities resources after regions but then my urls are not correct. How can i fix this?
回答1:
There is convention that you should not go more than 2 levels while generating routes unless its strictly needed.
I suggest you choose simple route for activity rather than 3 level of route :)
Still if you need then -
rake routes | grep activi
region_city_activities GET /regions/:region_id/cities/:city_id/activities(.:format) {:action=>"index", :controller=>"activities"}
POST /regions/:region_id/cities/:city_id/activities(.:format) {:action=>"create", :controller=>"activities"}
new_region_city_activity GET /regions/:region_id/cities/:city_id/activities/new(.:format) {:action=>"new", :controller=>"activities"}
edit_region_city_activity GET /regions/:region_id/cities/:city_id/activities/:id/edit(.:format) {:action=>"edit", :controller=>"activities"}
region_city_activity GET /regions/:region_id/cities/:city_id/activities/:id(.:format) {:action=>"show", :controller=>"activities"}
PUT /regions/:region_id/cities/:city_id/activities/:id(.:format) {:action=>"update", :controller=>"activities"}
DELETE /regions/:region_id/cities/:city_id/activities/:id(.:format) {:action=>"destroy", :controller=>"activities"}
rails c
-> app.polymorphic_path([Region.last, City.first, Activity.last])
=> "/regions/28/cities/1/activities/12"
-> app.polymorphic_path([Region.last, City.first, Activity.new])
=> "/regions/28/cities/1/activities"
来源:https://stackoverflow.com/questions/11948485/relationships-through-with-polymorphic-path