ruby - Rails: Calling Common Method to Edit Various Model Field -


i want create simple method initializing different counter fields users. however, i'm not sure how set value of field referred variable.

def self.initialize(user, field)   counter = "#{field}".to_sym   user.send(counter, nil)   user.save         end 

i tried:

  • user.counter instead of user.send(counter), comes undefined method error
  • user.send(counter) = nil, that's not correct syntax

ruby's accessors work using name= method attribute called name.

you can access way through model attributes interface:

user[counter] = nil user.save 

alternatively, more generic way should work on ruby object exposes attr_writer, attr_accessor, or equivalent:

user.send("#{counter}=", nil) user.save 

you'd use send version when dealing arbitrary method names, have here. converting to_sym not strictly necessary.

always careful white-list kinds of method calls you're accepting. shouldn't let counter arbitrary user parameter without validation.


Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -