简体   繁体   中英

Rails ActiveRecord Callbacks: Update if Exists, Create if Doesn't Exist

After combing through the documentation I am having a difficult time understand what callback I should be using.

pseudo code:

if child_id and outage_id don't exist

create a relationship (INSERT statement)

if outage_id is changed

modify relationship (UPDATE statement)

These inserts and updates are handled via collection_check_boxes

There are 3 models. Relationship, Outage, and Child.

class Outage < ApplicationRecord
  has_many :relationships
  has_many :children, through: :relationships
end

class Child < ApplicationRecord
end


class Relationship < ApplicationRecord
  belongs_to :outage
  belongs_to :child

  validate :check_if_exists, if: :outage_id_changed?

  private

  def check_if_exists
    Relationship.where(child_id: self.child_id).update_all(outage_id: self.outage_id)
  end
end

The issue I'm facing now is that an UPDATE always occurs right before the INSERT , no matter what. An UPDATE should only occur if the record exists and the outage_id is changed.

Any insight as to what I'm doing wrong here would be appreciated.

You can try this,

class Relationship < ApplicationRecord
    before_update :check_if_exists, if: :outage_id_changed?

    private
    def check_if_exists
       # Your logic
    end
end

Note: In your code check_if_exists will run on create also, since outage_id is changing from nil to <some_id> during create

However using before_update will make sure that its run only on update

Also note that you're using update_all which results in a direct db query and is not wrapped in transaction. Meaning, if at all update fails, changes made via update_all will not be rolled back

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM