Search code examples
ruby-on-railsrubyrestapiwebrequest

Ruby on rails : using update inside show for REST API


While accessing my REST API on rails I encountered that inside the rails console this can happen

variable = Model.find(1) //Random id
variable.update(:column => variable.column + 1) //my column is numeric

but this, while it is possible on console a cannot find a translation to my ruby API for this exact method

Any ideas?


Solution

  • Seems like you're trying to increment a counter whenever someone access your show method in a controller. That can be achieved with the increment! method from the ActiveRecord::Persistence class:

    instance = Model.find(params[:id])
    instance.increment!(:attribute_to_increment, by = 1)
    

    Note that the :attribute_to_increment has to be numeric.

    Source: https://apidock.com/rails/v4.2.7/ActiveRecord/Persistence/increment%21