僕のYak Shavingは終わらない

車輪の再発明をやめたらそこには壮大なYakの群れが

WEB+DB 詳解Ruby on Rails を流す その3 検索機能追加

ということで段々適当になってきました。さっさと終わらそう。

WEB+DB PRESS Vol.58

WEB+DB PRESS Vol.58


前回
WEB+DB 詳解Ruby on Rails を流す その2 コメント機能追加 - 僕の車輪の再発明
WEB+DBの詳解Rails3を流す その1 - 僕の車輪の再発明

今回はコードの変更のみ。

ちなみにコードは↓にあります。
kazuph/sample_rails_blog_app · GitHub

検索のViewの追加

app/views/posts/index.html.erb
<%= form_for @search_form, :url => posts_path, :html => {:method => :get} do |f| %>
  <%= f.search_field :q %>
  <%= f.submit '検索' %>
<% end %>

<h1>Listing posts</h1>

<table>
  <tr>
    <th>Title</th>
    <th>Body</th>
    <th></th>
    <th></th>
    <th></th>
  </tr>

<% @posts.each do |post| %>
  <tr>
    <td><%= post.title %></td>
    <td><%= post.body %></td>
    <td><%= link_to 'Show', post %></td>
    <td><%= link_to 'Edit', edit_post_path(post) %></td>
    <td><%= link_to 'Destroy', post, method: :delete, data: { confirm: 'Are you sure?' } %></td>
  </tr>
<% end %>
</table>

<br />

<%= link_to 'New Post', new_post_path %>

モデル追加

app/models/search_form.rb
#!/usr/bin/env ruby
# coding : utf-8
class SearchForm
  extend ActiveModel::Naming
  include ActiveModel::Conversion

  attr_accessor :q

  def initialize(params)
    self.q = params[:q] if params
  end

  def persisted?
    false
  end
end

コントローラー

app/controllers/posts_controller.rb
class PostsController < ApplicationController
  # GET /posts
  # GET /posts.json
  def index
    @search_form = SearchForm.new params[:search_form]
    @posts = Post.scoped
    
    if @search_form.q.present?
      @posts = @posts.title_or_body_matches @search_form.q
    end

    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @posts }
    end
  end
...
end

投稿のモデルに追記

app/models/post.rb
class Post < ActiveRecord::Base
  attr_accessible :body, :title
  has_many :comments
  validates :title,
    :presence => true,
    :length => {:maximum => 20}
  scope :title_or_body_matches, lambda{|q|
    where 'title like :q or body like :q', :q => "%#{q}%"
  }
end

はいできました~(適当)
f:id:kazuph1986:20121006222729j:plain