[英]Rails 4 - Passing parameter to controller method through link
我目前在我的应用程序中进行了相当丑陋的非规范化处理,在该应用程序中,我有7条路线,7个视图,7个控制器方法来显示.....等待它的结果.....在体育比赛中进行7轮比赛。
我想要一条路线,视图等...,然后从链接将参数传递到我的控制器方法中。
我的链接看起来像这样:
<li><%= link_to 'Round 1', round1_ownerships_path(rd_param: '1')%></li>
第一轮的定义如下:
def round1
foo = params[:rd_param]
@ownerships = Ownership.all.select { |m| m.round == foo}
end
路线如下所示(不要嘲笑新手!:)
resources :ownerships do
get 'last_three', on: :collection
get 'results', on: :collection
get 'round1', on: :collection
get 'round2', on: :collection
get 'round3', on: :collection
get 'round4', on: :collection
get 'round5', on: :collection
get 'round6', on: :collection
get 'round7', on: :collection
end
如果我仅将'foo'替换为1,则可以正常工作。 就目前而言,round1.html.erb视图将加载,但没有记录。 关于如何使它起作用的任何想法?
配置/ routes.rb中
Rails.application.routes.draw do
resources :ownerships do
get "rounds/:round", on: :collection, to: "ownerships#round", as: :round
end
./bin/rake路线
Prefix Verb URI Pattern Controller#Action
round_ownerships GET /ownerships/rounds/:round(.:format) ownerships#round
然后在您的控制器中
def round
@ownerships = Ownership.where(round: params[:round])
end
然后,您的round.html.erb
将仅遍历结果。
你会这样称呼它。
<% 1.upto(7) do |r| %>
<%= link_to "Round #{r}" round_ownerships_path(round: r) %>
<% end %>
我认为这将为您提供所需的东西。 如果不是,请使用缺少的内容更新问题。
但是阅读有关路由的Rails指南应该有助于阐明如何将URL与控件/参数进行匹配http://guides.rubyonrails.org/routing.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.