ruby-on-railsupdate-attributes

Rails common method for updating a database field


I am new to rails and I have a task to write a common method that will update a specific database field with a given value. And I should be able to invoke the method from anywhere in the app.(I understand about the security flaw and so on.. But I was asked to do it anyway) In my application controller I tried

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

Of course this doesn't work.. How to achieve this? What is the right way to do this? And if it is possible how to pass a model as an argument to a method?


Solution

  • 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, the first two approaches are significantly more expressive than the last - it is much more obvious what is happening. Not only that, but they are immediately more familiar to any Rails developer off the street, while the custom one has a learning curve. This, combined with the added code from the unnecessary method adds to the maintenance cost of the application. Additionally, the Rails methods are well tested and documented - are you planning to write that, too? Finally, the Rails methods are better thought out - for example, your prototype naively uses attribute validations, but does not check them (which could result in unexpected behavior) and makes more SQL queries than it needs to. It's fine to write custom methods, but let's not write arbitrary wrappers around perfectly fine Rails methods...