update attributes - Rails common method for updating a database field -


i new rails , have task write common method update specific database field given value. , should able invoke method anywhere in app.(i understand security flaw , on.. asked anyway) in application controller tried

  def update_my_model_status(model,id,field, value)     @model = model.find(id)     @model.update(field: value)   end 

of course doesn't work.. how achieve this? right way this? , if possible how pass model argument method?

if you're using rails, why not use rails?

compare update_all:

mymodel.where(id: 1).update_all(banned: true)

or maybe update_attribute:

my_model.update_attribute(:banned, true)

to:

update_my_model_status(mymodel, 1, :banned, true)

notice how, despite being shorter, first 2 approaches more expressive last - more obvious happening. not that, more familiar rails developer off street, while custom 1 has learning curve. this, combined added code unnecessary method adds maintenance cost of application. additionally, rails methods tested , documented - planning write that, too? finally, rails methods better thought out - example, prototype naively uses attribute validations, not check them (which result in unexpected behavior) , makes more sql queries needs to. it's fine write custom methods, let's not write arbitrary wrappers around fine rails methods...


Popular posts from this blog

php - How should I create my API for mobile applications (Needs Authentication) -

5 Reasons to Blog Anonymously (and 5 Reasons Not To)

Google AdWords and AdSense - A Dynamic Small Business Marketing Duo