Randy Burgess
Randy Burgess

Reputation: 5005

In my Rails app, JSON formatted results are appearing in a HTML view response

In a Rails 3.1 app, I have a controller returning a set of objects (children) in an index view using this code:

    def index
        @children = Child.all

        @base_class = "children-index"
        @title = "Your Children"

        respond_to do |format|
            format.html # children/index.html.erb
            format.json { render :json => @children }
        end
    end

The index.html.erb view is written like so:

<h1><%= title %></h1>
<ul>
  <%= @children.each do |child| %>
    <li><%= link_to child.fullname, child_path(child) %></li>
  <% end %>
</ul>

For some reason, the JSON response is getting thrown into the HTML response and I cannot determine the reason. None of my other index views are having this issue and their code is very close to the same.

John Jake Smith Jr

Jane Ann Doe

[#<Child id: 1, firstname: "John", middlename: "Jake", lastname: "Smith", suffix: "Jr", gender: "Male", dob_actual: "2011-01-05", dob_expected: "2011-01-01", height: 30, weight: 40, created_at: "2011-10-28 21:32:54", updated_at: "2011-10-28 21:32:54">, #<Child id: 2, firstname: "Jane", middlename: "Ann", lastname: "Doe", suffix: "", gender: "Female", dob_actual: "2011-05-05", dob_expected: "2011-05-01", height: 30, weight: 12, created_at: "2011-11-07 18:08:54", updated_at: "2011-11-07 18:08:54">]

Upvotes: 1

Views: 151

Answers (2)

yas375
yas375

Reputation: 3980

Did you forget to do @children.to_json in your controller?

Upvotes: 0

mu is too short
mu is too short

Reputation: 434985

That's not JSON, that's inspect output. You're getting that because each returns @children and you're using <%= here:

<%= @children.each do |child| %>

You want just this:

<% @children.each do |child| %>

Upvotes: 5

Related Questions