Search code examples
ruby-on-railsrubyruby-on-rails-3parameterslink-to

How can i add parameter to the given url which is dynamic in rails


I have page having url

http://localhost:3000/athletes/list

When user search on this page it changes to something like

http://localhost:3000/athletes/list?first_name=sachin&last_name=tendulkar

Where first_name and last_name are the search parameters when user search.

I want a link which add the parameter view_type=something in url for ex. For 1st URL

http://localhost:3000/athletes/list?view_type=something

For 2nd URL

http://localhost:3000/athletes/list?first_name=sachin&last_name=tendulkar&view_type=something

I have tried following

<%= link_to "Something ", :view_type => 'something' %>

But for both url it gives following url

http://localhost:3000/athletes/list?view_type=something

Solution

  • <%= link_to "Something ", params.merge(:view_type => 'something')  %>
    

    Though above code works in most of the cases for some reason it is giving error for some url may be because i am using friendly_url for ex.

    for url

    http://localhost:3000/athlete/sachin_ramesh_tendulkar_1
    

    giving me following wrong url

    http://localhost:3000/athlete/1?view_type=something
    

    To fixed this i am using javascript method as follows

    function something(){
        var par =""
        var link =window.location.href
        if (link.indexOf('view_type=something') == -1)
            par = link.indexOf('?') != -1 ? "&view_type=something" : "?view_type=something"
        window.location.href = link+par
    }
    

    and rails code

    <%= link_to "Something ", "javascript:void(0)", :onclick => "something();"  %>