Skip to content

Instantly share code, notes, and snippets.

@jwo
Created October 3, 2012 20:03
Show Gist options
  • Save jwo/3829489 to your computer and use it in GitHub Desktop.
Save jwo/3829489 to your computer and use it in GitHub Desktop.
Dynamic strong_parameters example

A Simple example on how to use strong_parameters, but have it be dynamic

Yes, it's easy to do... the only weird part is that the params.permit won't take an array, it wants a list of parameters. So we need to use the ruby syntax where we prepend the array with * to have that work.

Simple example of the splat.

def do_the_things(a, b, c)
  puts "c: #{c}"
  puts "b: #{b}"
  puts "c: #{c}"
end

do_the_things *[6, 7, 8]

without the *, you'll get a ArgumentError: wrong number of arguments (1 for 3) error.

Tests included!

class Post < ActiveRecord::Base
include ActiveModel::ForbiddenAttributesProtection
def self.attributes_for_user user
attrs = [:body, :title]
attrs << :published if user.admin?
attrs
end
end
class PostsController < ApplicationController
respond_to :html
def update
@post = Post.find(params[:id])
@post.update_attributes params.require(:post).permit(*Post.attributes_for_user(current_user))
respond_with @post
end
end
require 'test_helper'
#using mocha to stub PostsController#current_user
class PostsControllerTest < ActionController::TestCase
setup do
@post = Post.create do |p|
p.title = "the title"
p.body = "the body"
p.published = false
end
end
test "update post as admin" do
@user = User.create!(email: "[email protected]", admin: true)
@controller.stubs(:current_user).returns( @user )
put :update, id: @post.id, post: { title: "new title", body: "new body", published: true}
@post.reload
assert_equal true, @post.published
assert_equal "new title", @post.title
end
test "cannot update post as regular" do
@controller.stubs(:current_user).returns( User.create!(email: "[email protected]",
admin: false) )
put :update, id: @post.id, post: { title: "new title", body: "new body", published: true}
@post.reload
assert_equal false, @post.published
assert_equal "new title", @post.title
end
test "can update post title, body as regular" do
@controller.stubs(:current_user).returns( User.create!(email: "[email protected]",
admin: false) )
put :update, id: @post.id, post: { title: "new title", body: "new body"}
@post.reload
assert_equal "new title", @post.title
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment