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:
What do you think about the name of the method? Filter Parameters seemed to make sense, but it's a little generic.
Are there uses of this that I'm not thinking of and that would cause problems? For example, passing in nested attributes may not work.