Skip to content

Instantly share code, notes, and snippets.

@eladmeidar
Created August 25, 2014 16:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save eladmeidar/de49fab3701e669fee1b to your computer and use it in GitHub Desktop.
Save eladmeidar/de49fab3701e669fee1b to your computer and use it in GitHub Desktop.
Better Strong Params approach
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