当我尝试“全部”操作时会发生错误datamapper中的方法 [英] error happens when I try "all" method in datamapper
本文介绍了当我尝试“全部”操作时会发生错误datamapper中的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我尝试在Sinatra中执行此操作时,
When I try to do this in Sinatra,
class Comment
include DataMapper::Resource
property :id, Serial
property :body, Text
property :created_at, DateTime
end
get '/show' do
comment = Comment.all
@comment.each do |comment|
"#{comment.body}"
end
end
返回此错误,
ERROR: undefined method `bytesize' for #<Comment:0x13a2248>
有人能指出我正确的方向吗?
Could anyone point me to the right direction?
谢谢,
推荐答案
您收到此错误是因为Sinatra占用了返回路径的值并将其转换为字符串,然后再尝试将其显示给客户端。
Your getting this error because Sinatra takes the return value of a route and converts it into a string before trying to display it to the client.
我建议您使用视图/模板来实现目标:
I suggest you use a view/template to achieve your goal:
# file: <your sinatra file>
get '/show' do
@comments = Comment.all
erb :comments
end
# file: views/comments.erb
<% if !@comments.empty? %>
<ul>
<% @comments.each do |comment| %>
<li><%= comment.body %></li>
<% end %>
</ul>
<% else %>
Sorry, no comments to display.
<% end %>
或将注释附加到String变量中,并在完成后返回:
Or append your comments to a String variable and return it when your done:
get '/show' do
comments = Comment.all
output = ""
comments.each do |comment|
output << "#{comment.body} <br />"
end
return output
end
这篇关于当我尝试“全部”操作时会发生错误datamapper中的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文