Creating a Model manually

suggest change

Scaffolding 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

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents