Skip to content

Instantly share code, notes, and snippets.

@tkawa
Created July 11, 2013 07:57
Show Gist options
  • Save tkawa/5973433 to your computer and use it in GitHub Desktop.
Save tkawa/5973433 to your computer and use it in GitHub Desktop.
https://gist.github.com/tkawa/4745785 の件、FormBuilder(form_forみたいなやつ)がいらなければ、gemなくてもこんなふうに書けばすむというメモ。
class FilterParams < ActionController::Parameters
include ActiveModel::Model
validates :date, format: /\A\d{4}-\d{2}-\d{2}\Z/
validates :q, length: { maximum: 20 }
def initialize(params = {})
params.reverse_merge!(per: '10')
super(params)
end
def read_attribute_for_validation(key)
self[key]
end
end
class PostsController < ApplicationController
def index
@posts = if filter_params.valid? # バリデーション実行
Post.date(filter_params[:date]).search(filter_params[:q]).page(filter_params[:page]).per(filter_params[:per])
else
Post.none
end
end
def create
@post = Post.new(post_params)
if @post.save
redirect_to @post, notice: 'Post was successfully created.'
else
render action: "new"
end
end
private
def post_params
# これは普通のstrong_parametersの使い方
params.require(:post).permit(:title, :body, :tag, :date)
end
def filter_params
FilterParams.new(params).permit(:date, :q, :page, :per)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment