0

I have a controller that I want to have 2 responses, the generic html and the json. In my view, I want to have a link to said json. I saw in the apidoc, someone said you accomplish designating the format in the link_to by doing somethin like this.

<h3><%= link_to "Indexes" , 
        params.merge({:format => "json"}) , 
       state_laws_path %></h3>

However, everytime I visit the page this link is located on ( state_laws/index.html.erb ) I get the following error.

undefined method `stringify_keys' for "/state_laws":String

Extracted source (around line #3):
1: <h2>State Laws</h2>
2: <h3><%= link_to "Create State Law", new_state_law_path %></h3>
3: <h3><%= link_to "Indexes" , 
           params.merge({:format => "json"}) , 
           state_laws_path %>    </h3>
4: <ul id="state_laws">
5:   <% @state_laws.each do |law| %>
6:       <li class="<%= cycle("odd", "even") %>">

Does anyone have any ideas of how I can tell my view that I want a link that will go to the index action of the controller using the json format ? Any help is greatly appreciated.

1 Answer 1

3

Try this:

<%= link_to "Indexes", state_laws_path(params.merge(:format => "json")) %>

Passing the parameters to the state_laws_path method will make it return an URL that contains them. For instance, if your params contain {:foo => "bar"} and your state_laws_path is "/state_laws", the above call would return the path "/state_laws.json?foo=bar"

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. Someone needs to fix the comment or change the documentation found here, apidock.com/rails/ActionView/Helpers/UrlHelper/link_to especially Hannu's response since it it no longer valid.
It is maybe a little confusing, but not incorrect. The syntax that I've mentioned is covered

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.