Skip to content

Commit

Permalink
Allow #update to set column to nil (#369)
Browse files Browse the repository at this point in the history
  • Loading branch information
Blacksmoke16 authored and drujensen committed Oct 5, 2019
1 parent 162a9ff commit cbf7669
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 1 deletion.
10 changes: 10 additions & 0 deletions spec/granite/transactions/update_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,16 @@ describe "#update" do
Parent.find!(parent.id).name.should eq "Other parent"
end

it "allows setting a value to nil" do
model = Teacher.create!(name: "New Parent")

model.update(name: nil)

model.name.should be_nil

Teacher.find!(model.id).name.should be_nil
end

it "does not update an invalid object" do
parent = Parent.new(name: "New Parent")
parent.save!
Expand Down
2 changes: 1 addition & 1 deletion src/granite/columns.cr
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ module Granite::Columns

def set_attributes(hash : Hash(String | Symbol, Type)) : self
{% for column in @type.instance_vars.select { |ivar| (ann = ivar.annotation(Granite::Column)) && (!ann[:primary] || (ann[:primary] && ann[:auto] == false)) } %}
if hash.has_key?({{column.stringify}}) && !hash[{{column.stringify}}].nil?
if hash.has_key?({{column.stringify}})
begin
val = Granite::Type.convert_type hash[{{column.stringify}}], {{column.type}}
rescue ex : ArgumentError
Expand Down

0 comments on commit cbf7669

Please sign in to comment.