Say for example I pass the following two HTTP POST parameters to my Rails application:
fname=john&lname=doe
And within my application a controller will pass the params hash to the ‘Person’ model class defined as:
Class Person
attr_accessor :fname, :lname
def initialize(params)
@fname = params[:fname]
@lname = params[:lname]
end
end
As you can see I initialise a Person object with the values contained in the params hash. Note the name of properties and parameters are identical.
Obviously, in a real-world example I would have many more properties in my object, and so to use the above initialisation method could become tedious.
Therefore, I was wondering if there is a way to dynamically populate properties of an object with HTTP parameters of the same name?
You can do what you’re asking for in both controllers and models. First, an example of how this would work with a controller:
However, this is not a very practical application; there is very little reason to have accessor instance variables on a controller, much less enough that you would need to use this method.
Instead, what you seem to want to do is to create an instance of the
Personmodel and mass-assign attributes fromparams. Rails already does this, hence the defaultcreateaction:Note that by default, all model attributes are mass assignable. This can be a security issue when it becomes possible for users to manipulate certain fields (like associations). In this case, you can either whitelist or blacklist attributes on your models to prevent this type of security breach:
You can read more about mass assignment security here.
If you want to add this behavior to a group of non-ActiveRecord classes (without the protector attributes), you can snag this module and just do an
include MassAssignmentin your class definition (doesn’t rely on Rails):This avoids duplicating somewhat “ugly” code in every initializer.
Via: https://github.com/coreyward/typekit/blob/master/lib/typekit/base.rb