Skip to main content
3 of 3
deleted 19 characters in body; edited tags; edited title
Jamal
  • 34.9k
  • 13
  • 133
  • 237

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?