diff --git a/lib/avo/base_resource.rb b/lib/avo/base_resource.rb index 27e1b7cbff..828a5cb969 100644 --- a/lib/avo/base_resource.rb +++ b/lib/avo/base_resource.rb @@ -377,11 +377,9 @@ def hydrate_model_with_default_values !field.computed end .map do |field| - id = field.id value = field.value if field.type == "belongs_to" - id = field.foreign_key.to_sym reflection = @model._reflections[@params[:via_relation]] @@ -398,17 +396,15 @@ def hydrate_model_with_default_values end end - [id, value] + [field, value] end .to_h - .select do |id, value| + .select do |_, value| value.present? end - default_values.each do |id, value| - if @model.send(id).nil? - @model.send("#{id}=", value) - end + default_values.each do |field, value| + field.assign_value record: @model, value: value end end diff --git a/lib/avo/fields/base_field.rb b/lib/avo/fields/base_field.rb index a6a6a68fb1..3d1d8ffbba 100644 --- a/lib/avo/fields/base_field.rb +++ b/lib/avo/fields/base_field.rb @@ -273,6 +273,15 @@ def updatable !is_readonly? && visible? end + # Used by Avo to fill the record with the default value on :new and :edit views + def assign_value(record:, value:) + id = type == "belongs_to" ? foreign_key : database_id + + if record.send(id).nil? + record.send("#{id}=", value) + end + end + private def model_or_class(model) diff --git a/lib/avo/fields/location_field.rb b/lib/avo/fields/location_field.rb index 9d22f56864..03205ec7e2 100644 --- a/lib/avo/fields/location_field.rb +++ b/lib/avo/fields/location_field.rb @@ -73,6 +73,14 @@ def value_present? value.present? end + + def assign_value(record:, value:) + return super if stored_as.blank? + + stored_as.each_with_index do |database_id, index| + record.send("#{database_id}=", value[index]) + end + end end end end diff --git a/spec/system/avo/location_field_spec.rb b/spec/system/avo/location_field_spec.rb index 91b2d8ba7f..5af1e793bc 100644 --- a/spec/system/avo/location_field_spec.rb +++ b/spec/system/avo/location_field_spec.rb @@ -6,6 +6,14 @@ describe "without value" do let(:city) { create :city, latitude: nil, longitude: nil } + context "new" do + it "shows empty location field" do + visit "/admin/resources/cities/new" + + expect(find_field_element("coordinates")).to have_text "" + end + end + context "show" do it "shows empty location field" do visit "/admin/resources/cities/#{city.id}"