How to add parameter to rails index action / method?

I want to pass the parameter to the index action, but I only get 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 the url that submits to show the action instead, to index the action:

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

What should be added in the routes file or in the field of view?

The output of my routes:

 $ rake routes blog GET /blog(.:format) {:action=>"index", :controller=>"blog"} blog GET /blog/:id(.:format) {:action=>"show", :controller=>"blog"} 
+7
source share
3 answers

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

The desired route is blogs_path , and you can add a parameter to it, for example. blogs_path(other_item => :value) .

Exactly how it will depend on whether you are trying to use it in a controller, other representation, etc.

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

+9
source

It looks like you want 2 routes:

 /blogs/:other_param /blogs/:id 

But for someone as smart as Rails, he cannot determine if the parameter should be treated as other_param or as id.

So, the easiest solution is to add this route to the default settings:

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

So Rails knows that if you are going to / blogs / other _param / current, then it will handle the current as: other_param.

+1
source

Use the code below to pass the parameter:

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

or

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

the above code will redirect to the action of the index with the name as a key and check as a parameter,

+1
source

All Articles