sinatra - 我在datamapper中尝试 “all”方法时发生错误

标签 sinatra datamapper

当我尝试在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/

相关文章:

ruby-on-rails - 如何在 erb 模板中呈现数组的最佳方式?

ruby - Dashing 仪表板框架将标签和值传递给列表小部件

ruby - 加载错误 : no such file to load -- dm-sqlite-adapter

mysql - 在 Rails 应用程序中形成 SQL 查询

sinatra - 使用 Sinatra Server Sent Events 流时如何提高并发性

ruby - 每当 Amazon SQS 队列更新时运行 Ruby 任务

sinatra - Sinantra,如何在 POST 处理程序中访问 URL 参数,例如 "?something=xyz"(它不在 params[] 中)

php - 数据映射器模式、文件上传和原则 2 的单一责任原则

Ruby 组合数学

php - 为不同的数据库引擎实现数据映射器时如何防止重复?