Class: Terrazzo::Field::HasMany

Inherits:
Associative show all
Defined in:
lib/terrazzo/field/has_many.rb

Constant Summary collapse

DEFAULT_PER_PAGE =
5

Constants inherited from Base

Base::ABSTRACT_FIELD_CLASSES

Instance Attribute Summary

Attributes inherited from Base

#attribute, #data, #options, #page, #resource

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Associative

associative?, eager_load?

Methods inherited from Base

associative?, eager_load?, eager_load_association, #field_type, field_type, #form_input_attributes, #initialize, #required?, searchable?, transform_param, with_options

Constructor Details

This class inherits a constructor from Terrazzo::Field::Base

Class Method Details

.default_optionsObject



40
41
42
# File 'lib/terrazzo/field/has_many.rb', line 40

def default_options
  {}
end

.permitted_attribute(attr, _options = {}) ⇒ Object



44
45
46
# File 'lib/terrazzo/field/has_many.rb', line 44

def permitted_attribute(attr, _options = {})
  { "#{attr.to_s.singularize}_ids" => [] }
end

.sortable?Boolean

Returns:



36
37
38
# File 'lib/terrazzo/field/has_many.rb', line 36

def sortable?
  false
end

Instance Method Details

#current_pageObject



54
55
56
57
# File 'lib/terrazzo/field/has_many.rb', line 54

def current_page
  p = options[:_page].to_i
  p < 1 ? 1 : p
end

#page_recordsObject



67
68
69
70
71
72
73
# File 'lib/terrazzo/field/has_many.rb', line 67

def page_records
  @page_records ||= begin
    records = paginated.to_a
    preload_record_associations(records)
    records
  end
end

#per_pageObject



49
50
51
52
# File 'lib/terrazzo/field/has_many.rb', line 49

def per_page
  requested = (options[:per_page] || options[:limit] || DEFAULT_PER_PAGE).to_i
  requested.positive? ? requested : DEFAULT_PER_PAGE
end

#serializable_options(page = nil) ⇒ Object



24
25
26
27
28
29
30
31
32
33
# File 'lib/terrazzo/field/has_many.rb', line 24

def serializable_options(page = nil)
  opts = {}
  if page == :form && resource
    opts[:resourceOptions] = resource_options
  end
  if options.key?(:render_actions)
    opts[:renderActions] = options[:render_actions]
  end
  opts
end

#serialize_value(mode) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/terrazzo/field/has_many.rb', line 6

def serialize_value(mode)
  return nil if data.nil?

  case mode
  when :index
    count = data.size
    label = attribute.to_s.humanize.downcase
    label = label.singularize if count == 1
    { count: count, label: label }
  when :form
    data.map { |r| r.id.to_s }
  when :show
    serialize_show_value
  else
    data.map { |r| { id: r.id.to_s, display: display_name(r) } }
  end
end

#total_countObject



59
60
61
# File 'lib/terrazzo/field/has_many.rb', line 59

def total_count
  paginated.total_count
end

#total_pagesObject



63
64
65
# File 'lib/terrazzo/field/has_many.rb', line 63

def total_pages
  [paginated.total_pages, 1].max
end