Search code examples
ruby-on-railsrubymodelcontrollerput

Correct way to update a record while calling an instance method.


When I call update I don't want to just much update the record as I want to:

  1. Call a model function to update a property of the model.
  2. Update the model.

--

def update
    @simulation = Simulation.find(params[:id])
    @simulation.next # This is a function that has some logic to changes a property of the simulation record
    @simulation.update(simulation_params) 
end

Is this the correct way of going about this, or should I be using a separate controller function or another route?


Solution

  • Just for clarity, I personally would create an instance method in Simulation, high level code should be something like..

    #Simulation model
    class Simulation 
    
      ....
    
      def next_and_update(attrs)
        next
        update(attrs)
      end
    
    end
    
    #controller
    def update
      @simulation = Simulation.find(params[:id])
      @simulation.next_and_update(simulation_params)
    end
    

    Idea is, its ok to have 1-2 lines more, if you can read the code and understand whats happening.