# Cleaning parameters before passing them to a model

I'm writing an API and want to be able to pass in the attributes of a model without prefixing them with the name of the model.

I wrote this little extension to ActiveRecord in order to make it happen:

module ActiveRecord
class Base
def self.filter_attributes(hash)
hash.stringify_keys.slice(*self.accessible_attributes.to_a)
end
end
end


And I use it like this:

class IdeaController < ActiveRecord::Base
def create
@idea = Idea.create(Idea.filter_parameters(params))
respond_with @idea
end
end


I have two questions:

1. What do you think about the name of the method? filter_parameters() seemed to make sense, but it's a little generic.

2. Are there uses of this that I'm not thinking of and that would cause problems, such as passing in nested attributes?

• As Fivell says, it's pretty pointless. You're doing the same thing that the mass assignment protection is doing for you already. But if you want parameter filtering, instead of mass assignment filtering, you should look into using the strong_parameters gem, since it exists to do specifically that (and it may become a part of Rails 4). Oh, and by the way, your system doesn't allow role-based filtering - something the built-in mass assignment system does out of the box. – Flambino Oct 8 '12 at 21:27

@idea = Idea.create(Idea.filter_parameters(params))

@idea = Idea.create(params)