lib/avo/fields/belongs_to_field.rb in avo-3.0.0.pre12 vs lib/avo/fields/belongs_to_field.rb in avo-3.0.0.pre13

- old
+ new

@@ -102,13 +102,11 @@ nil end # What the user sees in the text field def field_label - value.send(target_resource.class.title) - rescue - nil + label end def options values_for_type end @@ -121,12 +119,12 @@ if attach_scope.present? query = Avo::ExecutionContext.new(target: attach_scope, query: query, parent: get_model).handle end - query.all.map do |model| - [model.send(resource.class.title), model.id] + query.all.map do |record| + [resource.hydrate(record: record).record_title, record.id] end end def database_value target_resource.id @@ -180,11 +178,11 @@ def relation_model_class @resource.model_class end def label - value.send(target_resource.class.title) + target_resource.hydrate(record: value).record_title end def to_permitted_param if polymorphic_as.present? return ["#{polymorphic_as}_type".to_sym, "#{polymorphic_as}_id".to_sym] @@ -195,22 +193,30 @@ def fill_field(model, key, value, params) return model unless model.methods.include? key.to_sym if polymorphic_as.present? - model.send("#{polymorphic_as}_type=", params["#{polymorphic_as}_type"]) + valid_model_class = valid_polymorphic_class params["#{polymorphic_as}_type"] + model.send("#{polymorphic_as}_type=", valid_model_class) + # If the type is blank, reset the id too. - if params["#{polymorphic_as}_type"].blank? + if valid_model_class.blank? model.send("#{polymorphic_as}_id=", nil) else model.send("#{polymorphic_as}_id=", params["#{polymorphic_as}_id"]) end else model.send("#{key}=", value) end model + end + + def valid_polymorphic_class(possible_class) + types.find do |type| + type.to_s == possible_class.to_s + end end def database_id # If the field is a polymorphic value, return the polymorphic_type as key and pre-fill the _id in fill_field. return "#{polymorphic_as}_type" if polymorphic_as.present?