繁体   English   中英

自定义动态路由并从URL获取ID

[英]Custom dynamic routing and get ids from url

我有一个模型名称“利润”,它有一个表名利润和表“product_id”,“client_id”,“grossprofit”的3列

现在在我的index.html.erb页面中,我有show as选项

<td><%= link_to 'Show', profit %></td>

当我点击节目链接时,我去显示页面和链接成为

http://localhost:3000/profits/1
http://localhost:3000/profits/2

这是我得到利润表的id,但我需要在我的网址中的product_id和client_id,如下所示

http://localhost:3000/profits/3/5

其中3将是product_id,5将是client_id

我需要做些什么来改变这个网址?如何在控制器的show动作中从url获取product_id和client_id?

模型之间的关联是

product: has_many  profits
client: has_many profits
profit: belongs to product and client

你在routes.rb文件中做错了路由请声明为:

resources :profits do
 resources :products, :clients
end

routes.rb

resources :profits do    
  get ":product_id/:client_id", :action => :show, :as => :show, :on => :collection
end

风景

<%= link_to 'Show', show_profits_path(profit.product_id, profit.client_id) %>

单击链接时的开发日志是

Started GET "/profits/5/3" for 127.0.0.1 at 2014-01-04 20:42:10 +0800
Processing by ProfitsController#show as HTML
  Parameters: {"product_id"=>"5", "client_id"=>"3"}

路线

正如HarsHarl&cenyongh建议的那样,你会更好地看待嵌套资源

您遇到的问题是您无法访问product_idclient_id变量,除非它们存储在会话中。 因此,您必须通过URL传递它们

我用这个:

resources :profits do
    get ":product_id/:client_id", to: "show"
end

这将创建此路线:

/profits/13/5

更重要的是,它会将这些参数: product_idclient_id传递给show动作

暂无
暂无

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

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