Fillype Farias
Fillype Farias

Reputation: 660

Json response on rails 6 from url with queries

Only on Rails 6 when:

I receives a json response on pages with url like:

www.site.com/foo

and not when url is like:

www.site.com/foo?q=x

to reproduce:

  1. rails new todo
  2. rails scaffold Todo task:string
  3. rails db:migrate

  4. rails server

  5. Create a task
  6. In file show.json.jbuilder you'll see:

    json.partial! "todos/todo", todo: @todo

  7. Go to show page (todo/1)

  8. Type on browser's console to se json response:

    $.ajax({ url: window.location.href + ".json", dataType: 'json', async: false });

When your url is "todo/1" jbuilder loads ok:

Started GET "/todos/1.json" for ::1 at 2019-10-28 13:55:54 -0300
Processing by TodosController#show as JSON
  Parameters: {"id"=>"1"}
  Todo Load (0.3ms)  SELECT "todos".* FROM "todos" WHERE "todos"."id" = ? LIMIT ?  [["id", 1], ["LIMIT", 1]]
  ↳ app/controllers/todos_controller.rb:67:in `set_todo'
  Rendering todos/show.json.jbuilder
  Rendered todos/_todo.json.jbuilder (Duration: 1.0ms | Allocations: 125)
  Rendered todos/show.json.jbuilder (Duration: 2.2ms | Allocations: 306)
Completed 200 OK in 10ms (Views: 3.9ms | ActiveRecord: 0.3ms | Allocations: 1565)

enter image description here

But if your url is "todo/1?q=foo" you have no data:

Started GET "/todos/1?q=foo.json" for ::1 at 2019-10-28 13:55:44 -0300
Processing by TodosController#show as JSON
  Parameters: {"q"=>"foo.json", "id"=>"1"}
  Todo Load (0.2ms)  SELECT "todos".* FROM "todos" WHERE "todos"."id" = ? LIMIT ?  [["id", 1], ["LIMIT", 1]]
  ↳ app/controllers/todos_controller.rb:67:in `set_todo'
  Rendering todos/show.html.erb within layouts/application
  Rendered todos/show.html.erb within layouts/application (Duration: 0.7ms | Allocations: 89)
Completed 200 OK in 25ms (Views: 21.3ms | ActiveRecord: 0.2ms | Allocations: 6547)

enter image description here

Obs: I opened this rails github issue

Upvotes: 0

Views: 729

Answers (2)

Fillype Farias
Fillype Farias

Reputation: 660

In order to work in rails 6.0.0 we need to explicitly tell to use json format when the url has queries:

todos_controller.rb

change from:

def show 
end

to:

def show
    respond_to do |format|
      format.html
      format.json
    end
end

Upvotes: 1

Samy Kacimi
Samy Kacimi

Reputation: 1238

This is because the request must be in the following form:

www.site.com/foo.json?q=x

If you want to pass parameters to the request, you can use the data parameter of ajax.

For instance:

$.ajax({
  url: "/todos",
  type: "GET",
  data: {
    id: 1,
    q: "x"
  },
  success: function (response) {
    console.log(response.data)
  }
})

Upvotes: 0

Related Questions