class Planter::Adapters::ActiveRecord
Default adapter for seeding Active Record tables.
When a table maps to an Active Record model, records are created through that model. Tables without a matching model, such as join tables, are seeded directly through the database connection.
Custom adapters should implement this public API:
-
+create_record(context:, lookup_attributes:, create_attributes:)+
-
+parent_ids(context:)+
-
+foreign_key(context:)+
-
+table_columns(context:)+
context is a Planter::SeedContext. Adapters are responsible for resolving those values into whatever persistence or reflection objects they need.
Public Instance Methods
Source
# File lib/planter/adapters/active_record.rb, line 36 def create_record(context:, lookup_attributes:, create_attributes:) if (model = model(context)) model .where(lookup_attributes) .first_or_create!(create_attributes) else create_table_record(context, lookup_attributes, create_attributes) end end
Create a record unless one already exists.
@param [Planter::SeedContext] context seeder configuration
@param [Hash] lookup_attributes attributes used to find the record
@param [Hash] create_attributes additional attributes used only when
creating a new record
@return [Object]
Source
# File lib/planter/adapters/active_record.rb, line 70 def foreign_key(context:) association_options(context).fetch(:foreign_key, "#{context.parent}_id") end
Return the foreign key used to assign a parent id on a child record.
The Active Record adapter resolves foreign keys through model associations. Tables without matching models should use a custom adapter for parent seeding.
@param [Planter::SeedContext] context seeder configuration
@return [String, Symbol]
Source
# File lib/planter/adapters/active_record.rb, line 56 def parent_ids(context:) parent_model(context).constantize.pluck(primary_key(context)) end
Return the parent ids to use when seeding child records.
The Active Record adapter resolves parents through model associations. Tables without matching models should use a custom adapter for parent seeding.
@param [Planter::SeedContext] context seeder configuration
@return [Array]
Source
# File lib/planter/adapters/active_record.rb, line 80 def table_columns(context:) ::ActiveRecord::Base.connection.columns(context.table_name).map(&:name) end
Return native table columns for the table being seeded.
@param [Planter::SeedContext] context seeder configuration
@return [Array<String>]
Source
# File lib/planter/adapters/active_record.rb, line 88 def table_names ::ActiveRecord::Base.connection.tables.reject do |table| %w[ar_internal_metadata schema_migrations].include?(table) end end
Return application table names that can have seeders generated.
@return [Array<String>]