はじめる!Rails3(1)14.7演習問題答え

14.7演習

1.書籍が出版年で昇順にソートされるようにbooks#index, books#checked_out アクション
を修正してください。


.order("publish_year ASC")

2.Book モデルにスコープchecked_out, checked_in を作り、 books コントローラを簡潔に書き換えなさい。


raw(links.join(" "))はIF文の外に


class Book < ActiveRecord::Base
scope :checked_out, where(:checked_out => true).order("publish_year ASC")
scope :checked_in, where(:checked_out => false).order("publish_year ASC")
end

new@book.checked_out = false

create@book = Book.create!(params[:book])
を修正

formの<%= form.hidden_field :checked_out %>も追加

3.タイトルで書籍を検索する機能を実装してください。


get :checked_out, :search, :on => :collection

scope :search, lambda { |query|
where([ "title LIKE ?", "%#{query}%" ])
}<%= form_tag [ :search, :books ], :method => :get,
:style => "text-align: right" do %>
<%= text_field_tag "query", params[:query] %>
<%= submit_tag "検索" %><% end %>


def search
@books = Book.checked_in
@books = @books.search(params[:query]) if params[:query].present?
render :action => "index"
end