T.J.
T.J.

Reputation: 1506

Ruby on rails : Avoiding inputs from user and doing a dry updation on models

I have made one update method inside Active record like this :-

class ActiveRecord::Base
  def status_update(new_status)
    return unless Helper.confirm_from_user?(new_status) # take input from user 
    ActiveRecord::Base.transaction do
      ## update logic
    end
  end
end

class Helper
  def self.confirm_from_user? value
    puts "Hi , Please check the value again #{value} "
    puts "Press y if you want to update"
    gets.chomp == "y" ? true : false
  end
end

If i have to update the status of my model . Then it will ask for conformation .

I am facing this problem that sometimes i have to do 1000 or more status updates for a model .

Car.where(:id => 1..1000).each{|car| car.status_update("checked") } .

Here i have to enter yes for all 1000 .

Please provide some good solutions(avoid flags) so that i get to know how my entity will look after updating and then i can confirm the changes . I will need old values and new values for some log creation .

Upvotes: 1

Views: 48

Answers (2)

Малъ Скрылевъ
Малъ Скрылевъ

Reputation: 16507

Please keep the model, controller and view separated, model not wasted by the foreign code. The user request and confirmation is for the view part, or just absent. So use in model/controller codes like follows:

class ModelWithConfirmation < class ActiveRecord::Base
   attr_accessor :confirmed

   before_validation {|record| record.confirmed? }
end

class CustomerController
   def mass_update
      ModelWithConfirmation.all.update_all(name: params[:name], confirmed: params[:confirmed])
   end
end

Then issue a request from console:

$ curl -v -H "Accept: application/json" -H "Content-type: application/json" -X POST \
       -d ' {"name":"Volodimir"}'  http://localhost:3000/customer/1/mass_update

Of course you need to setup the routes properly.

Or you just can update records with a single line from the rails or console:

ModelWithConfirmation.all.update_all(name: "Volodimir")
Car.where(:id => 1..1000).update_all(status: 'checked')

Upvotes: 0

Jiř&#237; Posp&#237;šil
Jiř&#237; Posp&#237;šil

Reputation: 14402

You can access the current object with self. Now all models include ActiveModel's utilities, you can use them to inspect the state of the object as follows:

c = Car.create! name: "Car 123"
c.name # => "Car 123"
c.changes # => {}
c.name = "Car 124"
c.changed? # => true
c.changes # => {"name"=>["Car 123", "Car 124"]}

Upvotes: 1

Related Questions