Billy Blob Snortin Billy Blob Snortin - 7 months ago 8
Ruby Question

How to know if instance was updated?

I have an

update
action that renders an
edit
action upon successful updates.

# PATCH/PUT /projects/1
# PATCH/PUT /projects/1.json
def update
respond_to do |format|
if @project.update(project_params)
format.html { render :edit, notice: 'Project was successfully updated.' }
else
format.html { render :edit }
end
end
end


In my view, I would like to do conditionally show/hide some page elements depending on if the
@project.update
was successful or not.

A solution I've considered is rewriting the method to something like:

# PATCH/PUT /projects/1
# PATCH/PUT /projects/1.json
def update
@was_successfully_updated = false # ADDED
respond_to do |format|
if @project.update(project_params)
@was_successfully_updated = true # ADDED
format.html { render :edit, notice: 'Project was successfully updated.' }
else
format.html { render :edit }
end
end
end


I feel like Rails may have something built in to indicate this.

Is there a way i can interrogate my
@project
instance to know:


  1. It's not a NEW unsaved record

  2. It contains data that was successfully updated


Answer

1. It's not a NEW unsaved record

@model.new_record?  # the opposite of `@model.persisted?`

2. It contains data that was successfully updated

@model.changes      # => {"column" => ["oldValue", "newValue"]}
Comments