Class: Uchi::Field::HasMany::Edit

Inherits:
Base::Edit show all
Defined in:
app/components/uchi/field/has_many.rb

Instance Attribute Summary

Attributes inherited from Base::Edit

#form, #hint, #label

Attributes inherited from Base::Component

#field, #record, #repository

Instance Method Summary collapse

Methods inherited from Base::Edit

#initialize

Methods inherited from Base::Component

#initialize, #value

Methods included from RoutesHelper

#uchi_path_to

Constructor Details

This class inherits a constructor from Uchi::Field::Base::Edit

Instance Method Details

#associated_records ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'app/components/uchi/field/has_many.rb', line 9

def associated_records
  records = field.value(record)
  return [] if records.nil?

  return Array(records) if field.nested_fields.any?

  # For a new, unsaved record, loading the association (e.g. via
  # #to_a, to apply sorting/includes) would query using a nil foreign
  # key, which can match unrelated rows with a NULL value there
  # instead of just returning none. Use the association's in-memory
  # target instead
  return record.association(field.name).target if record.new_record?

  associated_repository.find_all(scope: records)
end

#associated_repository ⇒ Object



25
26
27
28
29
30
31
# File 'app/components/uchi/field/has_many.rb', line 25

def associated_repository
  @associated_repository ||= begin
    model = reflection.klass
    repository_class = Uchi::Repository.for_model(model)
    repository_class.new(context: repository.context)
  end
end

#attribute_name ⇒ Object



33
34
35
# File 'app/components/uchi/field/has_many.rb', line 33

def attribute_name
  "#{field.name.to_s.singularize}_ids"
end

#dom_id_for_filter_query_input ⇒ Object



37
38
39
# File 'app/components/uchi/field/has_many.rb', line 37

def dom_id_for_filter_query_input
  "#{form.object_name}_#{attribute_name}_has_many_filter_query"
end

#dom_id_for_toggle ⇒ Object



41
42
43
# File 'app/components/uchi/field/has_many.rb', line 41

def dom_id_for_toggle
  "#{form.object_name}_#{attribute_name}_has_many_toggle"
end

#field_name_for_input ⇒ Object



45
46
47
# File 'app/components/uchi/field/has_many.rb', line 45

def field_name_for_input
  "#{form.object_name}[#{attribute_name}][]"
end

#record_title(record) ⇒ Object



49
50
51
52
53
# File 'app/components/uchi/field/has_many.rb', line 49

def record_title(record)
  return "" if record.nil?

  associated_repository.title(record)
end

#selected_titles ⇒ Object



55
56
57
# File 'app/components/uchi/field/has_many.rb', line 55

def selected_titles
  associated_records.map { |record| record_title(record) }.join(", ")
end