From ada8b022ab576371c1a9fa25b267e89d91fcef5f Mon Sep 17 00:00:00 2001 From: Matthew McGarvey Date: Wed, 18 Nov 2020 17:52:29 -0600 Subject: [PATCH] Allow insert giving default value (#540) --- spec/operations/save_operation_spec.cr | 8 ++++++++ spec/support/models/company.cr | 4 ++-- src/avram/save_operation.cr | 15 +++++++-------- 3 files changed, 17 insertions(+), 10 deletions(-) diff --git a/spec/operations/save_operation_spec.cr b/spec/operations/save_operation_spec.cr index 0aeb094d3..dfd1ac6c4 100644 --- a/spec/operations/save_operation_spec.cr +++ b/spec/operations/save_operation_spec.cr @@ -421,6 +421,14 @@ describe "Avram::SaveOperation" do end end + it "allows supplying a value that matches the default" do + result = Company::SaveOperation.create!(sales: 0_i64, earnings: 0_i64) + default_result = Company::SaveOperation.create! + + result.sales.should eq default_result.sales + result.earnings.should eq default_result.earnings + end + it "overrides all of the defaults through params" do published_at = 1.day.ago.to_utc.at_beginning_of_day drafted_at = 1.week.ago.to_utc.at_beginning_of_day diff --git a/spec/support/models/company.cr b/spec/support/models/company.cr index 809159ac5..cde21453d 100644 --- a/spec/support/models/company.cr +++ b/spec/support/models/company.cr @@ -1,6 +1,6 @@ class Company < BaseModel table do - column sales : Int64 - column earnings : Float64 + column sales : Int64 = 0_i64 + column earnings : Float64 = 0.0 end end diff --git a/src/avram/save_operation.cr b/src/avram/save_operation.cr index 11878232e..16df218d8 100644 --- a/src/avram/save_operation.cr +++ b/src/avram/save_operation.cr @@ -277,13 +277,7 @@ abstract class Avram::SaveOperation(T) end def changes : Hash(Symbol, String?) - _changes = {} of Symbol => String? - column_attributes.each do |attribute| - if attribute.changed? - _changes[attribute.name] = cast_value(attribute.value) - end - end - _changes + attributes_to_hash(column_attributes.select(&.changed?)) end macro add_cast_value_methods(columns) @@ -390,6 +384,11 @@ abstract class Avram::SaveOperation(T) end private def insert_sql - Avram::Insert.new(table_name, changes, T.column_names) + insert_values = attributes_to_hash(column_attributes).compact + Avram::Insert.new(table_name, insert_values, T.column_names) + end + + private def attributes_to_hash(attributes) : Hash(Symbol, String?) + attributes.map { |attribute| {attribute.name, cast_value(attribute.value)} }.to_h end end