Ruby on Rails上的掩码URL路径

时间:2015-03-23 16:34:24

标签: ruby-on-rails ruby routes

我试图屏蔽以下路线

get '/products/1' => 'products#show', :as => "map"

as hotels / 2 /在我的应用程序中映射,但我没有运气。我不确定我在这里做错了什么,因为它已经嵌套在酒店资源中。我在创建酒店时会自动创建两个产品,因此1个将是Map,2个将是App。

resources :hotels do

    resources :contacts
    resources :products

    get '/products/1' => 'products#show', :as => "map"

end

1 个答案:

答案 0 :(得分:0)

您所拥有的将在/hotels/:hotel_id/products/1(.:format)创建hotel_map_path。如果您想要没有hotel_prefix的map_path,则需要将地图路线移出酒店名称空间,如下所示:

resources :hotels do
  resources :contacts
  resources :products
end
get 'hotels/:hotel_id/products/1' => 'hotels/products#show', :as => "map"

希望有所帮助

修改

我要修改我的建议。您要做的是在路由和数据库存储(id)的细节之间创建依赖关系,这感觉不对。相反,我建议将该依赖项推送到active_record模型中,这是唯一应该负责了解酒店和产品如何保留的类。

所以,你的路线会是这样的:

resources :hotels do
  member do
   get :map
  end
  resources :contacts
  resources :products
end

应该给你

/hotels/:id/map

在您拥有的hotels_controller中

def map
  @hotel = Hotel.find(params[:id])
  @map = @hotel.location_map
end

在酒店模特中:

def map
  products.location_map
end

并在产品型号中:

def location_map
 ...
end

或者添加范围。

获得相同的路由效果更多线路,但不那么脆弱。