6
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Rails4でDBに依存しないモデルオブジェクトを作る

Last updated at Posted at 2014-12-16

はじめに

RailsはFormとDBの連携が簡潔便利に書けますが、
今回は中間モデルやコンバータ的に使えるモデルオブジェクトを作ります。

実装

Model

models/params/hoge.rb
# models/params/hoge.rb

module Params
  class HogeParam
    include ActiveModel::Model

    # 紐付くパラメータ群
    attr_accessor :name, :category

    # バリデーション定義
    validates :name, presence: true
    validates :category, presence: true
  end
end

Controller

controllers/fugas_controller.rb
# controllers/fugas_controller.rb

class FugasController < ApplicationController
  def index
    # リクエストパラメータからModelを生成
    @param = Params::HogeParam.new(params)
    
    # valid?でバリデーションを実行
    puts @param.valid? # => true | false
    
    # バリデーションの結果、エラーの場合はActiveModel::Errorsが入る
    puts @param.errors.messages # => {:name=>["can't be blank"]}
    
    render formats: [:json]
  end
end

参考

ActiveModel::Modelでは便利な機能が多数用意されているので、
公式リファレンスも参照ください。

http://api.rubyonrails.org/classes/ActiveModel/Model.html

6
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?