Relationships => through with polymorphic_path?

时光总嘲笑我的痴心妄想 提交于 2019-12-11 06:09:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!