Skip to content

Commit

Permalink
fix: location field new view (#1846)
Browse files Browse the repository at this point in the history
* fix: location field new view

* Update lib/avo/fields/base_field.rb

* rename method name

* use foreign_key to assign value for belongs_to fields

* add spec

---------

Co-authored-by: Adrian Marin <[email protected]>
  • Loading branch information
Paul-Bob and adrianthedev authored Jul 11, 2023
1 parent 35597f5 commit 9fccabf
Show file tree
Hide file tree
Showing 4 changed files with 29 additions and 8 deletions.
12 changes: 4 additions & 8 deletions lib/avo/base_resource.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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]]

Expand All @@ -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

Expand Down
9 changes: 9 additions & 0 deletions lib/avo/fields/base_field.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
8 changes: 8 additions & 0 deletions lib/avo/fields/location_field.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
8 changes: 8 additions & 0 deletions spec/system/avo/location_field_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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}"
Expand Down

0 comments on commit 9fccabf

Please sign in to comment.