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.counterinstead ofuser.send(counter), comes undefined method erroruser.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
Post a Comment