Last active
December 12, 2015 08:39
-
-
Save tkawa/4745785 to your computer and use it in GitHub Desktop.
http://example.com/posts?date=2013-01-01&q=search_word&page=2&per=20 のように、クエリパラメータでフィルタするような場合に、 strong parameters と併用して、 filter_params に default とか validate とか書けるgemを作成中ですがどうでしょう?
https://github.com/tkawa/collection_filter/tree/auto-params
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-# クエリパラメータもform_forと同じように書ける | |
= filter_form do |f| | |
= f.label :date | |
= f.text_field :date | |
= f.label :q | |
= f.search_field :q | |
= f.button |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
@_filter_params ||= begin | |
params.default( # デフォルト値が設定できる | |
per: '10' | |
).permit( | |
:date, :q, :page, :per | |
).validate( # モデルと同じようにバリデートできる | |
date: { format: /\A\d{4}-\d{2}-\d{2}\Z/ }, | |
q: { length: { maximum: 20 } } | |
) | |
end | |
end | |
helper_method :filter_params | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment