SeattleDucati
SeattleDucati

Reputation: 293

Rails 4 - Passing parameter to controller method through link

I currently have some rather ugly denormalization going on in my app, where I have 7 routes, 7 views, 7 controller methods to display the results of.....wait for it.....7 rounds in a sports draft.

I want to have a single route, view, etc...and pass a parameter into my controller method from a link.

My link looks like this:

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

The def for round 1 looks like this:

def round1
foo = params[:rd_param]
@ownerships = Ownership.all.select { |m| m.round == foo}
end

The routes look like this (No laughing at the newbie!:)

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

If I simply replace 'foo' with 1, it works fine. As it stands now, the round1.html.erb view loads, but there are no records. Any thoughts on how I can get this to work?

Upvotes: 1

Views: 68

Answers (1)

Doon
Doon

Reputation: 20232

config/routes.rb

Rails.application.routes.draw do
  resources :ownerships do
    get "rounds/:round", on: :collection,  to: "ownerships#round", as: :round
  end

./bin/rake routes

          Prefix Verb   URI Pattern                         Controller#Action
round_ownerships GET    /ownerships/rounds/:round(.:format) ownerships#round

then in your controller

def round
  @ownerships = Ownership.where(round: params[:round])
end

Then your round.html.erb would just iterate over the results.

and you would call it like this.

<% 1.upto(7) do |r| %>
   <%= link_to "Round #{r}" round_ownerships_path(round: r) %>
<% end %>

I think that would give you what you are looking for. if not please update the question with what is missing.

But reading the rails guides on routing should help shed some light on how to match urls to controls/params http://guides.rubyonrails.org/routing.html

Upvotes: 2

Related Questions