Creating a Model manually
suggest changeScaffolding is fast when you are new to Rails or starting an application. Later, creating the files yourself avoids trimming unused scaffold code.
Creating a model can be as simple as creating a file under app/models.
The most simple model, in ActiveRecord, is a class that extends ActiveRecord::Base.
class User < ActiveRecord::Base
end
Model files are stored in app/models/, and the file name corresponds to the singular name of the class:
# user
app/models/user.rb
# SomeModel
app/models/some_model.rb
The class will inherit all the ActiveRecord features: query methods, validations, callbacks, etc.
# Searches the User with ID 1
User.find(1)
The matching table must exist. Create it with a migration.
Generate the model and its migration together. The first argument is the model name, then each column is name:type with no commas:
rails g model ModelName column_name1:string column_name2:integer
A references column adds the foreign key:
rails g model ModelName column_name:string other_model:references
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents