Class: Planter::Adapters::ActiveRecord

Inherits:
Object
  • Object
show all
Defined in:
lib/planter/adapters/active_record.rb

Overview

Default adapter for seeding Active Record models.

Custom adapters should implement this public API:

  • create_record(model_name:, lookup_attributes:, create_attributes:)

  • parent_ids(model_name:, parent:)

  • foreign_key(model_name:, parent:)

  • table_columns(model_name:)

  • table_names

model_name is the configured seeder model name. parent is the configured parent association name. Adapters are responsible for resolving those values into whatever persistence or reflection objects they need.

Instance Method Summary collapse

Instance Method Details

#create_record(model_name:, lookup_attributes:, create_attributes:) ⇒ Object

Create a record unless one already exists.

Parameters:

  • model_name (String)

    the model being seeded

  • lookup_attributes (Hash)

    attributes used to find the record

  • create_attributes (Hash)

    additional attributes used only when creating a new record

Returns:

  • (Object)


30
31
32
33
34
# File 'lib/planter/adapters/active_record.rb', line 30

def create_record(model_name:, lookup_attributes:, create_attributes:)
  model_name.constantize
    .where(lookup_attributes)
    .first_or_create!(create_attributes)
end

#foreign_key(model_name:, parent:) ⇒ String, Symbol

Return the foreign key used to assign a parent id on a child record.

Parameters:

  • model_name (String)

    the model being seeded

  • parent (String, Symbol)

    the parent association name

Returns:

  • (String, Symbol)


56
57
58
# File 'lib/planter/adapters/active_record.rb', line 56

def foreign_key(model_name:, parent:)
  association_options(model_name, parent).fetch(:foreign_key, "#{parent}_id")
end

#parent_ids(model_name:, parent:) ⇒ Array

Return the parent ids to use when seeding child records.

Parameters:

  • model_name (String)

    the model being seeded

  • parent (String, Symbol)

    the parent association name

Returns:

  • (Array)


44
45
46
# File 'lib/planter/adapters/active_record.rb', line 44

def parent_ids(model_name:, parent:)
  parent_model(model_name, parent).constantize.pluck(primary_key(model_name, parent))
end

#table_columns(model_name:) ⇒ Array<String>

Return native table columns for the model being seeded.

Parameters:

  • model_name (String)

    the model being seeded

Returns:

  • (Array<String>)


66
67
68
# File 'lib/planter/adapters/active_record.rb', line 66

def table_columns(model_name:)
  model_name.constantize.column_names
end

#table_namesArray<String>

Return application table names that can have seeders generated.

Returns:

  • (Array<String>)


74
75
76
77
78
# File 'lib/planter/adapters/active_record.rb', line 74

def table_names
  ::ActiveRecord::Base.connection.tables.reject do |table|
    %w[ar_internal_metadata schema_migrations].include?(table)
  end
end