簡體   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