开发者

Bind paramerts in Object if those present there

I am receiving an API call at my server with parameters

first_name , :l开发者_JAVA技巧ast_name , :age

etc

I want to bind those params to my object against which user is having attribute with same name , like i want to have these in user[first_name] , user[:last_name]

so that I can just put the complete user object into database in following way ,

User.new(params[:user]) or User.new(some_hash)

I dont want to use the following ,

User.new(:first_name=>params[:first_name],:last_name=>params[:last_name]) 

thanks in advance for you help :)


Something like this may work:

user = User.new
params.each do |key,value|
  user[key] = value if user.attribute_names.include?(key.to_s)
end

Note, however, that you should protect sensitive attributes of your User model with attr_protected or attr_accessible in this case.


Writing that functionality into User.initialize can take care of this:

def initialize(args={})
  args.each_with_key do |key,val|
    instance_variable_set("@#{key}", val)
  end
end

This of course has no validation and does not protect your object from bad data. For example, if you want to make sure only valid accessible attributes are being set, add if respond_to? key to end end of line 3.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜