【问题标题】:In my Rails app, JSON formatted results are appearing in a HTML view response在我的 Rails 应用程序中,JSON 格式的结果出现在 HTML 视图响应中
【发布时间】:2011-11-08 04:19:29
【问题描述】:

在 Rails 3.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">]

【问题讨论】:

    标签: ruby-on-rails ruby view controller


    【解决方案1】:

    那不是 JSON,那是 inspect 输出。你得到这个是因为each 返回@children 而你在这里使用&lt;%=

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

    你只想要这个:

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

    【讨论】:

    • 所以,为了进一步解释, 执行代码中的指令,但 打印中间的内容。他们究竟如何称呼这些外壳?
    • @wrburgess:你说得对。抱歉,我不知道“事物”的任何标准名称。
    【解决方案2】:

    您是否忘记在控制器中执行@children.to_json

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-10-09
      • 1970-01-01
      • 2016-04-03
      • 2013-03-14
      • 1970-01-01
      • 2011-01-28
      • 1970-01-01
      相关资源
      最近更新 更多