谷歌图书的未定义方法

undefined method with googlebooks

我正在 sinatra 中构建一个库,使用 postresql 作为数据库并使用 'googlebooks' gem 来查找我想要的信息。

这是我在 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

这是我的 erb 文件 :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>

列表部分有效。我能够拥有一个包含标题列表的页面...问题是当我尝试从参数 isbn 调用数据时,我总是遇到此错误:

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

对可能的解决方案有什么想法吗?

根据 documentationGoogleBooks::Response 是枚举器。因此,您需要使用 each 对其进行迭代,并对从枚举器检索到的各个对象调用 title 方法。


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

变量名text书本上的细节不是一个好名字,你需要选择合适的变量名,很多时候好的变量名使调试更容易