Ruby on rails 自定义动态路由并从url获取ID
我有一个模型名“利润”,它有一个表名“利润”,表中有3列“产品id”、“客户id”、“grossprofit” 现在在我的index.html.erb页面中,我有了显示为的选项Ruby on rails 自定义动态路由并从url获取ID,ruby-on-rails,Ruby On Rails,我有一个模型名“利润”,它有一个表名“利润”,表中有3列“产品id”、“客户id”、“grossprofit” 现在在我的index.html.erb页面中,我有了显示为的选项 <td><%= link_to 'Show', profit %></td> 也就是说,我正在获取利润表的id,但我需要在我的url中包含产品id和客户id,如下所示 http://localhost:3000/profits/3/5 其中3为产品标识,5为客户标识 要获取此url
<td><%= link_to 'Show', profit %></td>
也就是说,我正在获取利润表的id,但我需要在我的url中包含产品id和客户id,如下所示
http://localhost:3000/profits/3/5
其中3为产品标识,5为客户标识
要获取此url,我必须做哪些更改?如何在控制器的显示操作中从url获取产品id和客户id
模型之间的关联是
product: has_many profits
client: has_many profits
profit: belongs to product and client
您在routes.rb文件中做了错误的路由,请声明为:
resources :profits do
resources :products, :clients
end
路线.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) %>
路线 正如Harshall&Cenyong建议的,你最好看看 您遇到的问题是无法访问
产品id
和客户id
变量,除非它们存储在会话中。因此,您必须通过URL传递它们
我会用这个:
resources :profits do
get ":product_id/:client_id", to: "show"
end
这将创建此路由:
/profits/13/5
更重要的是,它会将以下参数传递给show actionNeed your routes.erb文件,因为您所说的都没有说明为什么学生应该参与。很抱歉,这会带来利润。我更新了postAh来解释这一点,下面的@harshall建议就是你想去的地方。
resources :profits do
get ":product_id/:client_id", to: "show"
end
/profits/13/5