Rails - separate a model from a database session

I came across a scenario where in other languages โ€‹โ€‹I would separate the model object from the transaction, then I can change everything I want without worrying about updating the record automatically.

Question

  • Do the rails do not support attaching / detaching a model object?

  • Which alternative, just duplicate the object?

EDIT

Scenario

We are reading models from the database, and we want to make changes to them that will not be stored in the database at the end of the transaction. In Hibernate \ JPA etc. You disconnect the model (Entity), and there will be no changes.

Now you may ask, why not use Model.dup? The answer is that we still need the model identifier, but as soon as you assign the identifier, the rails assume that this instance is now a model and updates the record at the end of the transaction.

thank

+4
source share
2 answers

You can completely change the attributes of instances of the Rails model without saving these changes.

There are a couple of methods for changing model attributes , some of which automatically save changes to the database, while others simply change the values โ€‹โ€‹of the attributes of the in-memory instance.

#assign_attributes #<attribute>= . #save .

+2

, , (, self.save). , , , , nil ( ):

attr_accessor :prevent_save
validates :prevent_save, absence: true

def prevent_save!
  self.prevent_save = true
end

def do_something_safely

  prevent_save!

  self.other_attr = 'abc'

end

def accidentally_save
  # if prevent_save! has been previously called, 
  # validations will fail, and save! will raise an exception
  self.save!
end
0

Source: https://habr.com/ru/post/1694331/


All Articles