While using scaffolding is a fast and easy if you are new to Rails or you are creating a new application, later it can be useful just to do it on your own ato avoid the need to go through the scaffold-generated code to slim it down (remove unused parts, etc.).
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)
Note: Make sure that the table for the corresponding model exists. If not, you can create the table by creating a Migration
You can generate a model and it's migration by terminal from the following command
rails g model column_name1:data_type1, column_name2:data_type2, ...
and can also assign foreign key(relationship) to the model by following command
rails g model column_name:data_type, model_name:references