class Para::AttributeField::RelationField
Public Instance Methods
foreign_key()
click to toggle source
# File lib/para/attribute_field/relation.rb, line 10 def foreign_key @foreign_key ||= reflection && case reflection.macro when :belongs_to then reflection.foreign_key when :has_one then :"#{ reflection.name }_id" when :has_many then :"#{ reflection.name.to_s.singularize }_ids" end end
polymorphic_through_reflection?()
click to toggle source
# File lib/para/attribute_field/relation.rb, line 30 def polymorphic_through_reflection? !!(through_relation && reflection.source_reflection.options[:polymorphic]) end
reflection()
click to toggle source
# File lib/para/attribute_field/relation.rb, line 6 def reflection @reflection ||= model.reflect_on_association(name) end
through_reflection()
click to toggle source
# File lib/para/attribute_field/relation.rb, line 22 def through_reflection @through_reflection ||= through_relation && model.reflect_on_association(through_relation) end
through_relation()
click to toggle source
# File lib/para/attribute_field/relation.rb, line 18 def through_relation @through_relation ||= reflection.options[:through] end
through_relation_source_foreign_key()
click to toggle source
# File lib/para/attribute_field/relation.rb, line 26 def through_relation_source_foreign_key @through_relation_source_foreign_key ||= reflection.source_reflection.foreign_key end
Private Instance Methods
on_the_fly_creation(ids, &block)
click to toggle source
Takes an array of ids and a block. Check for each id if model exists and create one if not.
Example : [12, “foo”] will try to create a model with
'foo' as a name, title or any other attribute referenced in the `Para.config.resource_name_methods` configuration param.
# File lib/para/attribute_field/relation.rb, line 52 def on_the_fly_creation ids, &block Array.wrap(ids).each do |id| if !reflection.klass.exists?(id: id) resource = reflection.klass.new Para.config.resource_name_methods.each do |method_name| setter_name = :"#{ method_name }=" if resource.respond_to?(setter_name) resource.send(setter_name, id) # This check avoids multiple creation of the same resource with # a given attribute value and ensure all resources from the form # that reference that new resource name are associated to the # same parent resource. if (existing_resource = reflection.klass.find_by(method_name => id)) block.call(existing_resource, id) break elsif resource.save block.call(resource, id) break end end end end end end
resource_name(resource)
click to toggle source
# File lib/para/attribute_field/relation.rb, line 36 def resource_name(resource) Para.config.resource_name_methods.each do |method| return resource.send(method) if resource.respond_to?(method) end model_name = resource.class.model_name.human "#{ model_name } - #{ resource.id }" end