Search code examples
ruby-on-railslink-to

Sending a specific variable value for link_to method in Rails


Is there a way to send a specific variable value for link_to method in Rails? In my case I want a variable @result to be 5 instead of 10 when a user presses a link_to button.

<%= link_to t('meters'), full_report_path, class: 'btn btn-sm btn-success' %>

def full
  @result = 10
end

Solution

  • You need to just send params with the link_to , that's it, it will be available in the method.

    <%= link_to t('meters'), full_report_path(:result => 5), class: 'btn btn-sm btn-success' %>
    

    in your method,

    def full
      if params[:result].present? 
        @result = params[:result]
      else 
        @result = 10
      end
    end
    

    You can try by checking whether the method is called from link, by checking whether the params are present, if present 5 else 10. Thats it.

    http://apidock.com/rails/ActionView/Helpers/UrlHelper/link_to you can find it here.