Rails Model Reference


Premium Content - Free Preview

Terminal Commands

  • rails new store - Create a new Rails app from scratch in a new store folder.

The following commands are entered in the terminal in your app's directory:

  • bundle install - Install the gems (bundled Ruby libraries) for your Rails App.
  • rails generate model Product name:string - Create Product model with a column name (which will store strings of text).
  • rails g migration AddPriceToProducts price:integer - generates the migration file to add an integer price column to the product table.
  • rake db:migrate - Run migration files to apply changes to your database.
  • rake test - Run your application's tests.

Rails Console

You can connect with your app/database and perform standard CRUD operations in the Rails console. This is useful for trying code out.

  • rails console (or rails c) - Enter this command in your terminal to start the Rails console.
  • reload! - Enter this in your running Rails console to reload changes

(See Active Record Migrations and the Rails Command Line for more.)

CRUD

These are the 4 basic "CRUD" operations:

  • Create - Product .create(name: "Phonograph" , description: "Records sound" ) - Creates and saves a new record to the database. Use .new to instantiate an object without saving it until .save is called.
  • Read - There are many methods for reading data, such as:
    • products = Product .all - return collection of all products
    • products = Product .where(name: "Hammer" , price: 10) - returns all products with both these attributes
    • product = Product .find_by(name: "Cow" ) - returns first product named "Cow"
  • Update - After retrieving a record, you can modify and save it:
    product.description = "It moos"
    product.save
  • Delete - Don't like your Cow? You can remove it from the database: product.destroy

See Active Record Basics and Active Record Query Interface for more.


End of Free Content Preview. Please Sign in or Sign up to buy premium content.

Contact Us
Sign in or email us at [email protected]