Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow #update to set column to nil #369

Merged
merged 1 commit into from
Oct 5, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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