Created
August 25, 2014 16:28
-
-
Save eladmeidar/de49fab3701e669fee1b to your computer and use it in GitHub Desktop.
Better Strong Params approach
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 | |
# Automatically create the strong parameters required method | |
def PostsController.filter_parameters(options = {}) | |
options[:for] = [options[:for]] if options[:for].is_a?(Symbol) | |
options[:for].each do |action_name| | |
define_method("#{action_name.to_s}_params") do | |
base = options[:require].keys.first | |
params.require(base).permit(*options[:require][base]) | |
end | |
end | |
end | |
# Sample for a filter specification | |
filter_parameters for: :create, require: {post: [:body, :title]} | |
def new | |
@post = Post.new | |
end | |
# Sample method that uses that automatically created "create_params" method | |
def create | |
@post = Post.new(create_params) | |
@post.save | |
redirect_to new_post_url | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment