9

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"}
Michael Durrant
  • 93,410
  • 97
  • 333
  • 497
Ben
  • 25,389
  • 34
  • 109
  • 165

3 Answers3

10

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) %>

Michael Durrant
  • 93,410
  • 97
  • 333
  • 497
  • please see my routes output in edit. I try to do blogs_path('myparam' => :value) but it takes to show action – Ben Mar 20 '12 at 00:37
  • i get this routes also, but i bring only my 2 routes that i have problem with them – Ben Mar 20 '12 at 01:08
2

It sounds like you want 2 routes:

/blogs/:other_param
/blogs/:id

But, for as smart as Rails is, it can't figure out whether the param is meant to be treated as an other_param or as an id.

So the simplest solution is to add this route to the resources defaults like so:

resources :blogs
get "/blogs/other_param/:other_param", to: "blogs#index", as: "other_param_blogs"

That way Rails knows that if you're going to /blogs/other_param/current, then it will treat current as the :other_param.

evanbikes
  • 4,131
  • 1
  • 22
  • 17
1

Use below code to pass parameter:

<a href="/blog?name=test">My link </a>

or

<%= link_to "My link", blog_path(name: "test") %>

above code will redirect to index action with name as key and test as parameter,

puneet18
  • 4,341
  • 2
  • 21
  • 27