Tbpgr Blog

Ruby プログラマ tbpgr(てぃーびー) のブログ

Ruby on Rails | ActiveModel::ModelでDB以外のモデルを定義

概要

ActiveModel::ModelでDB以外のモデルを定義

内容

ActiveModel::ModelでDB以外のモデルを定義します。
これにより、検索フォーム等についてValidation等の機能や、
form_forタグなどを利用出来ます。

サンプル

signin_controller
require "pp"

class SigninController < ApplicationController
  skip_filter :authorize, :except=>:index
  skip_filter :authorize, :except=>:signin

  def index
    @signin_form ||= SigninForm.new(nil, nil)
    @message = flash[:message]
  end

  def signin
    @signin_form ||= SigninForm.new(params[:signin_form][:login], params[:signin_form][:password])
    unless @signin_form.valid?
      @message = @signin_form.errors.full_messages
      return render :action => 'index'
    end

    user = @signin_form.user
    session[:user_id] = user.id

    render_partial menu_display: true
    redirect_to controller: 'user',action: 'list'
  end

  def signout
    session[:user_id] = nil
    flash[:message] = "ログアウトしました"
    redirect_to :controller => 'signin', :action => 'index'
  end
end
/views/signin/index.html.haml
- provide(:title, "BookShelfSystem")
=form_for @signin_form, :url => {:action => 'signin'} do |signin_form|
  %p 
    =label_tag 'login', 'login'
    =text_field :signin_form, :login
  %p 
    =label_tag 'password', 'password'
    =password_field :signin_form, :password
  %p 
    =submit_tag 'submit'
/models/signin_form.rb
class SigninForm
  include  ActiveModel::Model
  attr_accessor :login, :password, :user
  validates :login, :presence => true
  validate :user_exists
  validates :password, :presence => true
  validate :user_authenticated

  def initialize(login, password)
    @login, @password = login, password
  end

  def user_exists
    @user = User.find_by login: login
    errors.add(:login, ":[#{@login}]は存在しないユーザーアカウントです") unless @user
  end

  def user_authenticated
    return unless @user
    errors.add(:password, ":パスワードが不正です") unless @user.authenticate(@password) 
  end
end