1

我的模型是:

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,而是我做了以下事情:

通过关联添加 has_many 到 Region

class Region < ActiveRecord::Base
  has_many :activities, :through => :cities
end


@activities = @region.activities.find_all_by_homepage_city(true)

但是当我调用变量@activities 时使用多态路径。

- @activities.each do |b|
              %li 
                =link_to b.name, polymorphic_path([@region, @city, b])

我收到消息 "not method for region_activity_path" 。这是正确的,因为没有资源:资源之后的活动:区域

resources :regions do 
  resources :cities do
  resources :activities 

我可以在区域之后添加活动资源,但我的网址不正确。我怎样才能解决这个问题?

4

1 回答 1

0

有一个约定,除非严格需要,否则在生成路线时不应超过 2 个级别。

我建议你choose simple route for activity而不是 3 级路线:)

如果你还需要的话——

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"
于 2012-08-14T11:44:46.370 回答