How to add parameter to rails index action/method?

Yosef picture Yosef · Mar 20, 2012 · Viewed 14.1k times · Source

I want to pass a parameter to the index action, but the I'm only getting the show action.

routes.rb:

Test1::Application.routes.draw do
  resources :blog
end

blog_controller.rb:

  def show
    # code
  end

  def index
    # code
  end

View url that send to show action instead to index action:

<a  href="/blog/myvar">  My link </a>

What should I add in routes file or in view?

Output of my routes:

$ rake routes

blog GET    /blog(.:format)          {:action=>"index", :controller=>"blog"}

blog GET    /blog/:id(.:format)      {:action=>"show", :controller=>"blog"}

Answer

Michael Durrant picture Michael Durrant · Mar 20, 2012

The command line will show you routes you can use with rake routes

The route you want is blogs_path and you can add a parameter on to that, e.g. blogs_path(other_item => :value).

Exactly how will depend on whether you are try to use it in a controller, another view, etc.

For the view have: <%= link_to 'My Link', blogs_path(:other_item => value) %>