rubypostgresqlgoogle-bookssinatra-activerecord

undefined method with googlebooks


I'm building a library in sinatra, using postresql as database and a 'googlebooks' gem to find the informations I want.

This is my code in main.rb

get '/list' do
  @books = GoogleBooks.search(params[:title])
  erb :list
end

get '/info/:isbn' do
  #this is to get the info from my database if there is any

   if book = Book.find_by(isbn: params[:isbn])
     @book_title = book.title
     @book_authors = book.author
     @book_year = book.year
     @book_page_count = book.page_count
     @book_id = book.id
     @book_isbn = book.isbn
  else
     #use the gem to look for the data

    text = GoogleBooks.search(params[:isbn])
    @book_title = text.title
    @book_author = text.authors
    @book_year = text.published_date
    @book_cover = text.image_link(:zoom => 2)
    @book_page_count = text.page_count
    @book_notes = text.description
   #and then store it into the database

   book = Book.new
   book.title = @book_title
   book.authors = @book_authors
   book.publish_date = @book_year
   book.image_link = @book_cover
   book.page_count = @book_page_count
   book.description = @book_notes
   book.isbn = params[:isbn]
   book.save
   @book_id = book.id

  end

 erb :info
end

This is my erb file :list

 <div class='list_by_title'>
   <% @books.each do |text| %>
     <ul>
       <li class='list_by_title'>
         <a href="/info/<%= text.isbn_10 %>"><%= text.title %>  (Authour: <%= text.authors %>)</a>
       </li>

     </ul>
    <%end%>
 </div>

The list part works.. I'm able to have a page with a list of titles... the problem is when I try to call the data from the params isbn, I always have this error:

  NoMethodError at /info/0596554877
 undefined method `title' for #<GoogleBooks::Response:0x007ff07a430e28>

Any idea for a possible solution?


Solution

  • As per documentation, GoogleBooks::Response is an enumerator. So you need to iterate over it by using each, and invoke the title method on individual objects retrieved from enumerator.


    result = GoogleBooks.search(params[:isbn])
    result.each do |text|
      @book_title = text.title
      ...
    end
    

    Variable name text for details about a book is not a good name, you need to pick apt variable names, many a times good variable names makes debugging easier