Class: Planter::Adapters::ActiveRecord
- Inherits:
-
Object
- Object
- Planter::Adapters::ActiveRecord
- 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
-
#create_record(model_name:, lookup_attributes:, create_attributes:) ⇒ Object
Create a record unless one already exists.
-
#foreign_key(model_name:, parent:) ⇒ String, Symbol
Return the foreign key used to assign a parent id on a child record.
-
#parent_ids(model_name:, parent:) ⇒ Array
Return the parent ids to use when seeding child records.
-
#table_columns(model_name:) ⇒ Array<String>
Return native table columns for the model being seeded.
-
#table_names ⇒ Array<String>
Return application table names that can have seeders generated.
Instance Method Details
#create_record(model_name:, lookup_attributes:, create_attributes:) ⇒ Object
Create a record unless one already exists.
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.
56 57 58 |
# File 'lib/planter/adapters/active_record.rb', line 56 def foreign_key(model_name:, parent:) (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.
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.
66 67 68 |
# File 'lib/planter/adapters/active_record.rb', line 66 def table_columns(model_name:) model_name.constantize.column_names end |
#table_names ⇒ Array<String>
Return application table names that can have seeders generated.
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 |