docs/developer/tutorial/model.mdx
To create a new model and database migration file, run the following command:
bin/rails g spree:model Spree::Brand name:string:index
This will create a couple of files:
app/models/spree/brand.rb - the model filedb/migrate/XXXXXXXXXXXXXX_create_spree_brands.rb - the database migration fileNow run the migration:
bin/rails db:migrate
This will create the table spree_brands with the column name in the database. The name column is indexed for faster lookups. Also the model file app/models/spree/brand.rb is created.
Now that the model file is created, let's add some additional functionality to it, starting with validations:
module Spree
class Brand < Spree::Base
# Validations
validates :name, presence: true
end
end
This is a standard Ruby on Rails ActiveRecord model. Let's break down each part:
Spree::Base to automatically inherit all Spree functionality. Also the model itself is namespaced under Spree:: module, so it's available as Spree::Brand in the application.validates :name, presence: true - using ActiveRecord validations to ensure that the name is present.