Skip to content

Commit

Permalink
Merge pull request #134 from Crecto/validate_virtual_fields
Browse files Browse the repository at this point in the history
validate virtual attributes
  • Loading branch information
fridgerator authored Nov 20, 2017
2 parents 008fce7 + 0f581c3 commit 63df015
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 3 deletions.
11 changes: 11 additions & 0 deletions spec/schema_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,17 @@ describe Crecto do

u.to_query_hash.should eq({:name => "tester", :things => 6644, :smallnum => nil, :nope => 34.99, :yep => nil, :some_date => nil, :pageviews => 1234567890, :unique_field => nil, :created_at => nil, :updated_at => nil})
end

it "should return virtual attributes if `include_virtual` is passed as true" do
u = User.new
u.name = "tester"
u.things = 6644
u.stuff = 2343
u.nope = 34.9900
u.pageviews = 1234567890

u.to_query_hash(true).should eq({:name => "tester", :things => 6644, :stuff => 2343, :smallnum => nil, :nope => 34.99, :yep => nil, :some_date => nil, :pageviews => 1234567890, :unique_field => nil, :created_at => nil, :updated_at => nil})
end
end

describe "#pkey_value" do
Expand Down
2 changes: 1 addition & 1 deletion src/crecto/changeset/changeset.cr
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ module Crecto

def initialize(@instance : T)
@class_key = @instance.class.to_s
@instance_hash = @instance.to_query_hash
@instance_hash = @instance.to_query_hash(true)
@source = @instance.initial_values

check_required!
Expand Down
4 changes: 2 additions & 2 deletions src/crecto/schema.cr
Original file line number Diff line number Diff line change
Expand Up @@ -220,11 +220,11 @@ module Crecto


# Builds a hash from all `CRECTO_FIELDS` defined
def to_query_hash
def to_query_hash(include_virtual=false)
query_hash = {} of Symbol => DbValue | ArrayDbValue

{% for field in CRECTO_FIELDS %}
if @@changeset_fields.includes?({{field[:name]}})
if include_virtual || @@changeset_fields.includes?({{field[:name]}})
query_hash[{{field[:name]}}] = self.{{field[:name].id}}
query_hash[{{field[:name]}}] = query_hash[{{field[:name]}}].as(Time).to_utc if query_hash[{{field[:name]}}].is_a?(Time) && query_hash[{{field[:name]}}].as(Time).local?
end
Expand Down

0 comments on commit 63df015

Please sign in to comment.