class SmartSeeds::Generator::ForeignKey

Public Class Methods

new(column, model) click to toggle source
Calls superclass method SmartSeeds::Generator::Integer::new
# File lib/smart_seeds/generator/integer/foreign_key.rb, line 6
def initialize(column, model)
  super
end

Public Instance Methods

foreign_key?() click to toggle source
# File lib/smart_seeds/generator/integer/foreign_key.rb, line 21
def foreign_key?
  true if associations_include_column?
end
generate_value() click to toggle source
# File lib/smart_seeds/generator/integer/foreign_key.rb, line 10
def generate_value
  klass = determine_klass

  if klass.ids.empty?
    raise ActiveRecord::ActiveRecordError,
          "There are no records in #{camelized_model_name}. You have to add those first. You can run SmartSeeds.plant(#{camelized_model_name})"
  else
    klass.ids.sample
  end
end

Private Instance Methods

associations_include_column?() click to toggle source
# File lib/smart_seeds/generator/integer/foreign_key.rb, line 46
def associations_include_column?
  model_associations.map(&:name).include?(column_name_without_id.to_sym)
end
camelized_model_name() click to toggle source
# File lib/smart_seeds/generator/integer/foreign_key.rb, line 50
def camelized_model_name
  # converts underscore words like big_category to BigCategory constant
  camelize(column_name_without_id).constantize
end
column_name_without_id() click to toggle source
# File lib/smart_seeds/generator/integer/foreign_key.rb, line 42
def column_name_without_id
  column.name.sub(/^*_id/, '')
end
determine_klass() click to toggle source
# File lib/smart_seeds/generator/integer/foreign_key.rb, line 27
def determine_klass
  assocation = model_associations.select { |obj| obj.name == column_name_without_id.to_sym }

  # if a class_name has been overrided in a model's class
  if assocation.first.options.key? :class_name
    assocation.first.options[:class_name].constantize
  else
    camelized_model_name
  end
end
model_associations() click to toggle source
# File lib/smart_seeds/generator/integer/foreign_key.rb, line 38
def model_associations
  model.reflect_on_all_associations(:belongs_to)
end