Module: Binda::FieldableAssociations

Extended by:
ActiveSupport::Concern
Included in:
Board, Component, Repeater
Defined in:
app/models/concerns/binda/fieldable_associations.rb

Overview

Fieldable associations are Binda’s core feature.

They provide classes like ‘Binda::Component` and `Binda::Board` with a collection of fields

(texts, assets, dates and so on) to store data in a simple yet powerful way.

Instance Method Summary collapse

Instance Method Details

#find_or_create_a_field_by(field_setting_id, field_type) ⇒ Object

Find or create a field by field setting and field type

This is used in Binda’s editor views.

Please, check the code to know more about the way this method works as it’s pretty complex yet important.

Parameters:

  • field_setting_id (string)

    The field setting id

  • field_type (string)

    THe field type



101
102
103
104
105
106
107
# File 'app/models/concerns/binda/fieldable_associations.rb', line 101

def find_or_create_a_field_by(field_setting_id, field_type)
	if FieldSetting.get_field_classes.include?( field_type.classify ) && field_setting_id.is_a?( Integer )
		get_field(field_type, field_setting_id)
	else
		raise ArgumentError, "One parameter in find_or_create_a_field_by() is not correct on instance (#{self.class.name} ##{self.id}).", caller
	end
end

#generate_fieldsObject

This method is called upon the creation/update of a fieldable record (component, board or repeater)

and generates all fields related to each field settings which belongs to it.

This avoids any situation in which, for example, a component have a field setting for a text

but there is no text (meaning `Binda::Text` instance) that correspond to that field setting.
This causes issues when looping a bunch of components which will thow a error if you try to access
a component field, as some might have it some might not. This make sure that you can always expect 
to find a field instance which might be empty, but certainly it exists.

TODO check if find_or_create_a_field_by method should be used instead (it’s used in editors views)



120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
# File 'app/models/concerns/binda/fieldable_associations.rb', line 120

def generate_fields
# If this is a component or a board
	if self.respond_to?('structure')
 	field_settings = FieldSetting.where(field_group_id: FieldGroup.where(structure_id: self.structure.id))
 	field_settings.each do |field_setting|
 		"Binda::#{field_setting.field_type.classify}".constantize.find_or_create_by!(
 			fieldable_id: self.id, fieldable_type: self.class.name, field_setting_id: field_setting.id )
 	end
	# If this is a repeater
	else
		self.field_setting.children.each do |field_setting|
 		"Binda::#{field_setting.field_type.classify}".constantize.find_or_create_by!(
 			fieldable_id: self.id, fieldable_type: self.class.name, field_setting_id: field_setting.id )
		end
 end
end