简体   繁体   English

在Rails路由中使用参数生成URL

[英]Using Params in Rails Routes for generating url

I have a scoped route: 我有一条作用域内的路线:

 scope :path => ":db", :defaults => {:db => "default"} do
   resources :boxes
 end

That generates 那产生

    boxes GET    /:db/boxes(.:format)          {:db=>"default", :action=>"index", :controller=>"boxes"}
         POST   /:db/boxes(.:format)          {:db=>"default", :action=>"create", :controller=>"boxes"}
 new_box GET    /:db/boxes/new(.:format)      {:db=>"default", :action=>"new", :controller=>"boxes"}
edit_box GET    /:db/boxes/:id/edit(.:format) {:db=>"default", :action=>"edit", :controller=>"boxes"}
     box GET    /:db/boxes/:id(.:format)      {:db=>"default", :action=>"show", :controller=>"boxes"}
         PUT    /:db/boxes/:id(.:format)      {:db=>"default", :action=>"update", :controller=>"boxes"}
         DELETE /:db/boxes/:id(.:format)      {:db=>"default", :action=>"destroy", :controller=>"boxes"}

I would like to be able to call boxes_url (for example) and have it infer that the value for :db should be inferred from the current request. 我希望能够调用box_url(例如),并让它推断出:db的值应该从当前请求中推断出来。

Example: 例:

A request is made for "/lax/boxes". 请求“ / lax / boxes”。 In the template, I call box_url(@box), and it generates the url "/lax/boxes/1" (where @box.id = 1). 在模板中,我调用box_url(@box),它生成URL“ / lax / boxes / 1”(其中@ box.id = 1)。

The only solution I currently see is to always include params[:db] in url, calling box_url(params[:db],@box). 我目前看到的唯一解决方案是始终在URL中包含params [:db],并调用box_url(params [:db],@ box)。

Does anyone know anyway to get the behavior I've described? 有人知道反正得到我描述的行为吗?

This (in a helper file) should work: (在帮助文件中)应该可以工作:

def box_url(box)
    super(params[:db], box)
end

Unfortunately, you'll have to repeat this for each url/path you want to override. 不幸的是,您必须对要覆盖的每个URL /路径重复此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM