E
E
Evgeny Vlasov2017-04-14 19:38:52
ruby
Evgeny Vlasov, 2017-04-14 19:38:52

How to unsave an object in Rails?

Hello!
There is such a situation:

class CheckerResult < ApplicationRecord
  has_many :checker_errors, dependent: :destroy
  ###
end
class CheckerError < ApplicationRecord
  belongs_to :checker_result
  ###
end

checker_result = CheckerResult.new(...)

# Создается несколько таких checker_error
checker_result.checker_errors.new(...)
checker_result.checker_errors.new(...)

checker_result.save

It is necessary that checker_error has some method that checks the value of the field, and depending on its value, can delete itself (cancel the creation), somehow ignore the creation.
Schematically:
class CheckerError < ApplicationRecord
  belongs_to :checker_result
  ###
  def delete_if_some
    отменить_создание_себя if условие
  end
end

Tried these options:
before_create do
  throw(:abort) if условие
end

before_create do
  destroy if условие
end

but they don't fit.
Probably not explained very clearly. Thanks in advance!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
Karim Kyatlottyavi, 2017-04-14
@constXife

We wrap the code in a transaction to be able to undo the changes.

ActiveRecord::Base.transaction do
  checker_result.save
end

In the right place, we call ActiveRecord::Rollback and the transaction is canceled.
class CheckerError < ApplicationRecord
  belongs_to :checker_result

  def delete_if_some
    raise ActiveRecord::Rollback 
  end
end

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question