Skip to content

Commit

Permalink
Do not update created_at on update (#324)
Browse files Browse the repository at this point in the history
  • Loading branch information
Blacksmoke16 authored Feb 26, 2019
1 parent 040f1c1 commit 75e8473
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 2 deletions.
21 changes: 21 additions & 0 deletions spec/granite/transactions/update_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,27 @@ describe "#update" do

Parent.find!(parent.id).name.should eq "New Parent"
end

context "when created_at is nil" do
it "does not update created_at" do
parent = Parent.new(name: "New Parent")
parent.save!

created_at = parent.created_at!.at_beginning_of_second

# Simulating instantiating a new object with same ID
new_parent = Parent.new(name: "New New Parent")
new_parent.id = parent.id
new_parent.new_record = false
new_parent.updated_at = parent.updated_at
new_parent.save!

saved_parent = Parent.find!(parent.id)
saved_parent.name.should eq "New New Parent"
saved_parent.created_at.should eq created_at
saved_parent.updated_at.should eq Time.utc_now.at_beginning_of_second
end
end
end

describe "#update!" do
Expand Down
10 changes: 8 additions & 2 deletions src/granite/transactions.cr
Original file line number Diff line number Diff line change
Expand Up @@ -125,9 +125,15 @@ module Granite::Transactions

private def __update
set_timestamps mode: :update
fields = self.class.content_fields
fields = self.class.content_fields.dup
params = content_values + [@{{primary_name}}]

# Do not update created_at on update
if created_at_index = fields.index("created_at")
fields.delete_at created_at_index
params.delete_at created_at_index
end

begin
@@adapter.update @@table_name, @@primary_name, fields, params
rescue err
Expand Down Expand Up @@ -239,7 +245,7 @@ module Granite::Transactions
# Returns true if this object hasn't been saved yet.
@[JSON::Field(ignore: true)]
@[YAML::Field(ignore: true)]
getter? new_record : Bool = true
property? new_record : Bool = true

# Returns true if this object has been destroyed.
@[JSON::Field(ignore: true)]
Expand Down

0 comments on commit 75e8473

Please sign in to comment.