Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

error happens when I try "all" method in datamapper

When I try to do this in 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>

Could anyone point me to the right direction?

Thanks,

like image 954
toniowhola Avatar asked Jul 13 '09 00:07

toniowhola


1 Answers

Your getting this error because Sinatra takes the return value of a route and converts it into a string before trying to display it to the client.

I suggest you use a view/template to achieve your goal:

# file: <your sinatra file>
get '/show' do
  @comments = Comment.all
  erb :comments
end

# file: views/comments.erb
<% if [email protected]? %>
  <ul>
    <% @comments.each do |comment| %>
      <li><%= comment.body %></li>
    <% end %>
  </ul>
<% else %>
    Sorry, no comments to display.
<% end %>

Or append your comments to a String variable and return it when your done:

get '/show' do
  comments = Comment.all

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

  return output
end
like image 57
Luke Antins Avatar answered Jan 02 '23 21:01

Luke Antins