Rails Generators

Scaffolding

rails g scaffold [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

Migrations

Reference: Ruby Docs

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'

Routing

Shallow Routes

Routing hierarchy quickly gets complicated. One of the strategies suggested by the Rails Guide is to use shallow routing where you split your routes into logical and reasonable structures

Dynamically calling variables and their methods

You can dynamically call methods in Ruby and this is super helpful for testing. Let’s say you have a User class with name and email as it’s methods. You can call it dynamically in your code as the following:

user = User.new
user.email = '[email protected]'
eval("user").send("email") = '[email protected]'

Common Display Conventions

Adding commas to large numbers

<%= number_with_precision(@number, precision: 2, delimiter: ',') %>

Changing cases for string

Downcase

Changes all letters to be lower case

Upcase

Changes all letters to be upper case

Titleize

Changes the first letter of every word to be upper case

Camelize

Changes the first letter of every sentence to be upper case