当我在datamapper中尝试"all"方法时会发生错误

ton*_*ola 6 datamapper sinatra

当我在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>
Run Code Online (Sandbox Code Playgroud)

有人能指出我正确的方向吗?

谢谢,

Luk*_*ins 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 %>
Run Code Online (Sandbox Code Playgroud)

或者将您的注释附加到String变量并在完成后返回:

get '/show' do
  comments = Comment.all

  output = ""
  comments.each do |comment|
    output << "#{comment.body} <br />"
  end

  return output
end
Run Code Online (Sandbox Code Playgroud)