Photo by Aaron Santelices on Unsplash
Rails 7 Model Scaffold Options
The documentation on scaffolding attributes for models seems sparse or non-existent. This article lists what field types and options exist.
It is possible to have Rails automatically generate your model schema migration file using the provided model generators.
An example:
% rails generate model Post title:string
invoke active_record
create db/migrate/20220608155046_create_posts.rb
create app/models/post.rb
invoke test_unit
create test/models/post_test.rb
create test/fixtures/posts.yml
Looking at the migration file we'll see:
class CreatePosts < ActiveRecord::Migration[7.0]
def change
create_table :posts do |t|
t.string :title
t.timestamps
end
end
end
We can see our string title there. What happens if we try a type that makes no sense?
% rails generate model Blog title:varchar
Could not generate field 'title' with unknown type 'varchar'.
It'll raise an error and will not generate any scaffolding.
So what are the valid types and options then?
First of all, these are the valid types:
attachment
attachments
belongs_to
boolean
date
datetime
decimal
digest
float
integer
references
rich_text
string
text
time
timestamp
token
Secondly it is possible to specify an index (which can be unique too):
% rails generate model Order number:string:index
...
class CreateOrders < ActiveRecord::Migration[7.0]
def change
create_table :orders do |t|
t.string :number
t.timestamps
end
add_index :orders, :number
end
end
% rails generate model Organisation identifier:string:uniq
...
class CreateOrganisations < ActiveRecord::Migration[7.0]
def change
create_table :organisations do |t|
t.string :identifier
t.timestamps
end
add_index :organisations, :identifier, unique: true
end
end
For string
, text
, binary
and integer
it is possible to set a limit:
% rails generate model Vehicle code:string{10}
...
class CreateVehicles < ActiveRecord::Migration[7.0]
def change
create_table :vehicles do |t|
t.string :code, limit: 10
t.timestamps
end
end
end
For decimal
it is possible to set the precision and scale:
% rails generate model Product price:decimal{19.4}
...
class CreateProducts < ActiveRecord::Migration[7.0]
def change
create_table :products do |t|
t.decimal :price, precision: 19, scale: 4
t.timestamps
end
end
end
For references
and belongs_to
it is possible to indicate that it is a polymorphic association:
% rails generate model Comment commentable:references{polymorphic}
...
class CreateComments < ActiveRecord::Migration[7.0]
def change
create_table :comments do |t|
t.references :commentable, polymorphic: true, null: false
t.timestamps
end
end
end