Skip to content

Commit

Permalink
Allow insert giving default value (#540)
Browse files Browse the repository at this point in the history
  • Loading branch information
matthewmcgarvey authored Nov 18, 2020
1 parent c5443e3 commit ada8b02
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 10 deletions.
8 changes: 8 additions & 0 deletions spec/operations/save_operation_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions spec/support/models/company.cr
Original file line number Diff line number Diff line change
@@ -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
15 changes: 7 additions & 8 deletions src/avram/save_operation.cr
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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

0 comments on commit ada8b02

Please sign in to comment.