当我尝试在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>
有人能指出我正确的方向吗?
谢谢,
答案 0 :(得分:14)
您收到此错误是因为Sinatra获取路由的返回值并将其转换为字符串,然后尝试将其显示给客户端。
我建议您使用视图/模板来实现目标:
# 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变量并在完成后返回:
get '/show' do
comments = Comment.all
output = ""
comments.each do |comment|
output << "#{comment.body} <br />"
end
return output
end