Motivation: while using scaffolding is very nice if you are new to Rails or if your application is just starting out, later it can be useful just to do it on your own, avoiding 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
. You need nothing else to use it from other places.
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)
Additionally, create your migration to create the backing database table for your new model; see below.