Tutorial by Examples

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 c...
Ruby on Rails provides a model generator you can use to create ActiveRecord models. Simply use rails generate model and provide the model name. $ rails g model user In addition to the model file in app/models, the generator will also create: the Test in test/models/user_test.rb the Fixtures ...
Add/remove fields in existing tables Create a migration by running: rails generate migration AddTitleToCategories title:string This will create a migration that adds a title column to a categories table: class AddTitleToCategories < ActiveRecord::Migration[5.0] def change add_column...
A callback is a method that gets called at specific moments of an object's lifecycle (right before or after creation, deletion, update, validation, saving or loading from the database). For instance, say you have a listing that expires within 30 days of creation. One way to do that is like this: ...
Specially useful for has_and_belongs_to_many relation, you can manually create a join table using the create_table method. Suppose you have two models Tags and Proyects, and you'd like to associate them using a has_and_belongs_to_many relation. You need a join table to associate instances of both c...
Testing your Active Record models through your command line interface is simple. Navigate to the app directory in your terminal and type in rails console to start the Rails console. From here, you can run active record methods on your database. For example, if you had a database schema with a User...
Let's say you have a User model class User < ActiveRecord::Base end Now to update the first_name and last_name of a user with id = 1, you can write the following code. user = User.find(1) user.update(first_name: 'Kashif', last_name: 'Liaqat') Calling update will attempt to update the gi...

Page 1 of 1