关系 =>通过polymorphic_path? [英] Relationships => through with polymorphic_path?
问题描述
我的模型是:
class City < ActiveRecord::Base
belongs_to :region
has_many :activities
has_many :restaurants
end
class Activity < ActiveRecord::Base
belongs_to :city
end
我想访问所有城市的所有活动.从上一个关于 stackoverflow 的问题中,我读到我不能这样做@cities.activities,而是我做了以下事情:
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:
通过关联到 Region 添加 has_many
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)
但是当我调用变量@activities 时,使用 polymorphic_path.
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])
我收到消息不是 region_activity_path 的方法".这是正确的,因为没有资源:资源之后的活动:区域
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?
推荐答案
有一个约定,除非严格需要,否则在生成路由时不应超过 2 个级别.
There is convention that you should not go more than 2 levels while generating routes unless its strictly needed.
我建议你选择简单的活动路线
而不是3级路线:)
I suggest you choose simple route for activity
rather than 3 level of route :)
如果你需要的话 -
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"
这篇关于关系 =>通过polymorphic_path?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!