当我尝试在DataMapper的“所有”的方法发生错误(error happens when I t

2019-09-18 10:26发布

当我尝试这样做在西纳特拉,

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>

任何人都可以点我朝着正确的方向?

谢谢,

Answer 1:

您收到此错误,因为西纳特拉需要路由的返回值,并将其转换为一个字符串试图将其显示到客户端之前。

我建议你使用一个视图/模板来实现你的目标:

# 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 %>

或追加您的意见给一个字符串变量并返回它,当你完成:

get '/show' do
  comments = Comment.all

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

  return output
end


文章来源: error happens when I try “all” method in datamapper