modelのvalidateでしりとり改

http://shokai.mag.keio.ac.jp/shiritori/

migrate

class CreateWords < ActiveRecord::Migration
  def self.up
    create_table :words do |t|
      t.text :item

      t.timestamps
    end
  end

  def self.down
    drop_table :words
  end
end

word model

class Word < ActiveRecord::Base

  validates_presence_of :item, :message => '入力されていません'
  validates_uniqueness_of :item, :message => 'すでに使われた言葉です'

  def validate
    if item =~ /.*[んン]$/
      errors.add(:item, "負けを認めてください")
    end
    
    w = Word.find(:first, :order => "id DESC")
    return if w == nil # 1個目の時は良し

    if (item =~ /#{w.item[-1,1]}.*/) == nil # 最後の文字が同じでない時
      errors.add(:item, "しりとりしてください。前の人は#{w.item}です")
    end
  end
  
end