ActiveRecord

Sep 5, 2021

Reference: cdesch cheatsheet on GitHub

Rails Generators

Generating a model

rails g model [model name in singular] field_name:field_type

Common field types are

:string, :text, :integer, :float, :decimal, :datetime, :timestamp, :time, :date, :binary, :boolean, :references

Special examples

  • prices:decimal{8.2} can be used for prices
  • address:references will automatically create a relationship between your model and another model. In this example, you're creating a reference from your model to the address table

Note

You can use the same syntax for generating a scaffold which also includes the creation of controllers and views as well

Generating a migration

Reference: Ruby Docs

Migrations are changes made to existing models

rails g migration [Some context]To[Model name] field_name:field_type

Foreign References

rails generate migration AddAddressRefToContacts address:references

Dates

Reference: Ruby Docs

Creating a date

variable_name = Date.parse('December 23, 2019')

Returning values

variable_name.strftime('%B') returns 'December'

See RubyDocs for more examples

Relationships

References

Generating References

You can generate a reference through a rails generator

rails g migration AddPostToUsers post:references

By default, Rails 5 will make this relationship a required field by the model. However, you can override it at the model level

class User < ApplicationRecord
end

class Post < ApplicationRecord
  belongs_to :user, required: true
end

Reference: thejspr

You may want to create a reference that has a different name from the model name. To do that, you will need to tweak the migration file

class AddCreatorToOrders < ActiveRecord::Migration[5.2]
  def change
    add_reference :orders, :creator, foreign_key: { to_table: :users }
  end
end

You will then need to modify the models to reflect the relationship

belongs_to :creator, class_name: 'User'

Tags

Great! You've successfully subscribed.
Great! Next, complete checkout for full access.
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.