在我的 Rails 应用程序中,JSON 格式的结果出现在 HTML 视图响应中
在 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">]
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">]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这不是 JSON,而是
inspect
输出。您之所以得到这个,是因为each
返回@children
并且您在此处使用<%=
:您只需要这样:
That's not JSON, that's
inspect
output. You're getting that becauseeach
returns@children
and you're using<%=
here:You want just this:
您是否忘记在控制器中执行
@children.to_json
操作?Did you forget to do
@children.to_json
in your controller?