フォームに定型文を入れる仕掛けを考える

カテゴリー(選択肢)とメモ(自由入力)があるようなDBの入力フォームがあるとして、頻繁に入力する定型文が偶に現れる。季節的なモノなのでカテゴリーに含めるのはためらうというか集計の関係もあるので入れたくない。
そこで定型文フィールドを作成して、ボタンを押したらメモ欄に追記されるような仕掛けはどうだろうか?定型文はユーザーに作成してもらって、管理の手間は無くしたい。

テーブルの用意

定型文=phrase(s)テーブルと命名
コンソールでコマンド実行

$rails generate migration CreatePhrases
      invoke  active_record
      create    db/migrate/20140228013211_create_phrases.rb

create_phrases.rbが出来た。

class CreatePhrases < ActiveRecord::Migration
  def up
  end

  def down
  end
end

Up,DownよりもChangeが好みなので作り変えます。
思いつくままに作成してみます。

class CreatePhrases < ActiveRecord::Migration
  def change
    create_table :phrases do |t|
     t.integer :staff_id, :null=>false #スタッフID
     t.text :sentence, :null=>false #定型文
     t.string :target_db, :null=>false #対象DB
     t.boolean :view, :null=>false #表示/非表示
     t.text :memo #メモ
     t.timestamps
    end
  end
end

コンソールでコマンド実行

$ rake db:migrate
==  CreatePhrases: migrating ==================================================
-- create_table(:phrases)
   -> 0.1390s
==  CreatePhrases: migrated (0.1390s) =========================================

モデル作成

app/modes/phrase.rb作成
パラメータを受け取れるscopeを作る。
scopeに条件分岐も加えられると知って大喜びで実装する。

#encoding: utf-8
class Phrase < ActiveRecorde::Base
  validates :staff_id, :sentence, :target_db, :view, :presence => true
  scope :available, lambda{|db|
    where("target_db =? AND view=1", db)
    }
  scope :hoge, lambda{|hoge|
    where("hoge = ?", hoge) unless hoge.blank?
    }
end

コントローラ作成

とりあえず動作確認できるぶんだけ

#encoding: utf-8
class PhrasesController < ApplicationController
  def list
  end
end

**ビュー作成
app/views/phrases/list.html.erb
>||
#からっぽ

http://localhost:3000/phrases/list
アクセスしてレイアウトファイルだけ表示されていれば、ひとまずOK

挿入の仕掛け

定型句の入力編集はできるようになったので、ブチ込む仕掛けにとりかかる。
 
アプリケーションヘルパーにコントローラーとか指定して汎用性をチョビっと追求してみた。

#application_helper.rb
module ApplicationHelper
  #定型文の選択肢作成
  def select_phrase
    phrase = Phrase.available(params[:controller])

    unless phrase.nil?
     sellist=[["",""]]
     #長文を短縮形で表示したい
     phrase.each{|ph|
        sellist.push([ph.sentence, truncate(ph.sentence)])
        }
      return "<br>"+select_tag("phrase", options_for_select(sellist))+content_tag(:span, "挿入", :class=>"button_link", :id=>"insert_phrase")
    end
  end
end

呼び出し方法

# _form.html.erb
<%== select_phrase %>

ボタンの実装

jQueryで値を取得、ID値がコントローラー毎に異なるので無理やり実装したらこうなった。

//aplication.js
$(document).ready(function(){
  $("#insert_phrase").click(function(){
    var res, con;
//selectの選択肢を取得
    var sele = $("#phrase").val();
//表示しているフォームを値で取得、空だと何も入らない
    if(res=$("#hoge_content").val()){con="#hoge_content";}
    if(res=$("#fuga_memo").val()){con="#fuga_memo";}
    $(con).append(sele);
  });	
});

定型句を先に入力することができないのは仕方ない。