Sha256: 3e6cf6f6232087d17f2730b7117626e50e2cd819f04d6a55478e72675efd3179

Contents?: true

Size: 1.4 KB

Versions: 4

Compression:

Stored size: 1.4 KB

Contents

module Binda
	class FieldGroup < ApplicationRecord

		# Associations
		belongs_to :structure

		# use destroy not delete_all otherwise the field settings 
		# won't be able to delete all their dependent content
		has_many :field_settings, dependent: :destroy

		# Validations
		validates :name, presence: true
		validates :slug, uniqueness: true
		accepts_nested_attributes_for :field_settings, allow_destroy: true, reject_if: :is_rejected

		# Slug
		extend FriendlyId
		friendly_id :default_slug, use: [:slugged, :finders]

		after_create :update_position

		# Friendly id preference on slug generation
		#
		# Method inherited from friendly id 
		# @see https://github.com/norman/friendly_id/issues/436
	  def should_generate_new_friendly_id?
	    slug.blank?
	  end

		# Set slug name
		#
		# It generates 4 possible slugs before falling back to FriendlyId default behaviour
		def default_slug
			[ "#{ self.structure.name }-#{ self.name }",
				"#{ self.structure.name }-#{ self.name }-1",
				"#{ self.structure.name }-#{ self.name }-2",
				"#{ self.structure.name }-#{ self.name }-3" ]
		end

		#
		# Sets the validation rules to accept and save an attribute
		def is_rejected( attributes )
			attributes['name'].blank? && attributes['field_type'].blank?
		end

		private 

			def update_position
				if self.position.nil?
					self.update_attribute( 'position', self.structure.field_groups.length )
				end
			end

	end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
binda-0.1.3 app/models/binda/field_group.rb
binda-0.1.2 app/models/binda/field_group.rb
binda-0.1.1 app/models/binda/field_group.rb
binda-0.1.0 app/models/binda/field_group.rb