2015-09-09 29 views
1

我目前有一些相當醜陋的反規範化在我的應用程序中進行,其中我有7個路線,7個視圖,7個控制器方法來顯示結果.....等待它..... 7輪在體育草案。Rails 4 - 通過鏈接傳遞參數給控制器方法

我想有一個單一的路線,查看等...並從鏈接傳遞參數到我的控制器方法。

我的鏈接看起來是這樣的:

<li><%= link_to 'Round 1', round1_ownerships_path(rd_param: '1')%></li> 

圓1的高清看起來是這樣的:

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 

如果我簡單地用1代替'foo',它可以正常工作。現在,加載round1.html.erb視圖,但沒有記錄。關於如何讓這個工作的任何想法?

+0

您的所有權模式有圓一些輕?你試圖從那一輪獲得所有的所有權? – Doon

+0

或者您是否試圖獲得給定所有權的每輪迴合的結果,因爲您目前擁有所有權下的回合? – Doon

回答

2

的config/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 %> 

我認爲這會給你你在找什麼。如果不是,請更新缺少的內容。

但閱讀佈線導軌導向應該幫助闡明如何搭配的URL控制/ PARAMS http://guides.rubyonrails.org/routing.html

+0

Doon,我現在在滅火,我會盡快測試你的迴應。謝謝! – SeattleDucati

+0

這工作完美。我根本無法感謝你。這不僅工作,但你的答案真的幫助我瞭解路由。非常感謝! – SeattleDucati

相關問題