在Rails3.1应用程序中,我有一个控制器使用以下代码在索引视图中返回一组对象(子对象):

    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

index.html.erb视图的编写方式如下:
<h1><%= title %></h1>
<ul>
  <%= @children.each do |child| %>
    <li><%= link_to child.fullname, child_path(child) %></li>
  <% end %>
</ul>

出于某种原因,JSON响应被抛出到HTML响应中,我无法确定原因我的其他索引视图都没有这个问题,它们的代码也非常接近。
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">]

最佳答案

这不是JSON,这是inspect输出你得到这个结果是因为each返回@children并且你在这里使用<%=

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

你只要这个:
<% @children.each do |child| %>

09-04 08:14
查看更多