我正在sinatra建立一个库,使用postresql作为数据库和'googlebooks'宝石来查找我想要的信息。
这是我在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>
列表部分有效..我能够有一个包含标题列表的页面...问题是当我尝试从params isbn调用数据时,我总是有这个错误:
NoMethodError at /info/0596554877
undefined method `title' for #<GoogleBooks::Response:0x007ff07a430e28>
对于可能的解决方案有任何想法吗?
答案 0 :(得分:0)
根据documentation,GoogleBooks::Response
是一个枚举器。因此,您需要使用each
对其进行迭代,并对从枚举器检索的各个对象调用title
方法。
result = GoogleBooks.search(params[:isbn])
result.each do |text|
@book_title = text.title
...
end
变量名text
有关书籍的详细信息并不是一个好名字,您需要选择apt变量名称,很多次好的变量名称使调试更容易