Skip to content

Instantly share code, notes, and snippets.

@buren
Last active December 24, 2020 11:59
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save buren/0d3c4270a473252a4e9a to your computer and use it in GitHub Desktop.
Save buren/0d3c4270a473252a4e9a to your computer and use it in GitHub Desktop.
A simple pattern to refactor permitted params for Rails with StrongParameters included.
# Rails StrongParameters refactor
#
# Inspired by Ryan Bates's Screencast #371
# http://railscasts.com/episodes/371-strong-parameters
#
# A simple pattern to refactor permitted params for Rails with StrongParameters.
# app/models/author.rb
class Author < ActiveRecord::Base
validates_presence_of :name, :birth_date
end
# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
helper_method :permitted_params # Include this line if you'd like to access the permitted params form a view template
def permitted_params
@permitted_params ||= Params::Permitted.new(params, current_user)
end
end
class AuthorsController < ApplicationController
def create
@author = Author.new(permitted_params.author)
# ... omitted for brevity
end
end
# app/models/params/permit_params.rb
module Params
class PermitParams < Struct.new(:params, :user)
# List of all models which have a param class defined in app/models/params/
PARAM_MODELS = [:author]
PARAM_MODELS.each do |model|
include "Params::#{model.to_s.titleize.gsub(/ /, '')}".constantize
define_method(model) do
model_params = params.fetch(model, ActionController::Parameters.new)
model_params.permit(*send("#{model}_attributes"))
# You could instead, permit all params for an admin user and
# only check permitted atributes otherwise.
#
# if user.admin?
# model_params.permit!
# else
# model_params.permit(*send("#{model}_attributes"))
# end
end
end
end
end
# app/models/params/author.rb
module Params
module Author
def author_attributes
[:name, :birth_date] if user.author?
end
end
end
@momer
Copy link

momer commented Jan 25, 2015

One of the main points of Strong Parameters is to move the responsibility outside of the model and into the controller; otherwise, attr_accessible would suffice. This just moves that around in a backwards way to some Module.

For some controllers with nested params duplication, this may be fine, but this is a rare circumstance.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment