当我尝试在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
It returns this error,
ERROR: undefined method `bytesize' for #<Comment:0x13a2248>
谁能指出我正确的方向?
谢谢,
最佳答案
之所以收到此错误,是因为Sinatra会获取路由的返回值并将其转换为字符串,然后再尝试将其显示给客户端。
我建议您使用 View /模板来实现您的目标:
# 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
关于sinatra - 我在datamapper中尝试 “all”方法时发生错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1117272/