Skip to content

Instantly share code, notes, and snippets.

@drakmail
Forked from ingmarsk/Rails cheatsheet
Created March 29, 2018 14:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save drakmail/2882b5f41fdcb5cad4496335b64fc183 to your computer and use it in GitHub Desktop.
Save drakmail/2882b5f41fdcb5cad4496335b64fc183 to your computer and use it in GitHub Desktop.
Rails cheatsheet

rails s (start server)
rails console
rake about (app desc)
rake db:schema:dump (connecto db & export schema)
rake db:migrate:status
rake db:migrate (apply migrations to db)
rake db:migrate VERSION=0 (rollback)
rake db:migrate:(up/down/redo) VERSION=
rake db:seed (populate db with test data from seeds.rb)
rake db:rollback (rollback the migration)
rake test (run tests)
rake test:controllers (run just the functional tests)
rake test:models (run just the unit tests)
rake log:clear LOGS=test
rails destroy controller controller_name
bundle exec rake

rake -T (list all available tasks)

Solving Migrations Problems
——————————————————-———————-
If we run into a bug in our migrations code it can leave our migration in a broken state
where we cannot migrate either up or down…

  • Go to the migration file that is causing the problem and temporally comment out executed code lines to get back on track
  • Write SQL commands as a last resort
  • Keep migrations small and concise (no create 4 tables in one migration)
  • Test all migrations in development before production

Table migration methods
——————————————————-————
create_table “table” do |t|
t.column “name”, :type, options
t.type “name”, options (short v)
end

drop_table(table)
rename_table(table, new_name)

Column migration methods
——————————————————-—————
add_column(table, column, type, options)
remove column(table.column)
rename column(table, column, new_name)
change_column (table, column, type, options)

execute(“raw SQL”)

Index migration methods
——————————————————-————
add_index(table, column, options)
options… :unique => true/false && :name => “index_custom_name”
remove_index(table, column)

Table column options
————————————————————
:limit => size
:default => value
:null => true/false
:precision => number
:scale => number

Table column types
——————————————————
string
text
time
date
datetime
boolean
integer
float
decimal
binary

Creating records
————————————————

  • New/save: instantiate object – set values – save
  • Create: instantiate & set vaues & save

Updating records
————————————————

  • Find/save: find record – set values – save
  • Find/update_attributes: find record – set values & save

Deleting records
-———————

  • Find/destroy

match ‘:controller(/:action(/:id))’, :via => :get

Rails Web Servers
——————————————————

  • Apache 2 + Passenger/mod_rails (most commonly used)
  • Nginx (Engine X)
  • Lighttpd
  • Mongrel
  • WEBrick

ps
kill -s SIGKILL
kill -9 PID

Create a new Mysql User:

GRANT ALL PRIVILEGES ON db_name.* TO ’username’@’localhost’ IDENTIFIED BY ‘password’;
SHOW GRANTS FOR ’username’@’localhost’;
SELECT user, host FROM mysql.user;

ActiveRecord
-—————
Rails implementation of active record pattern for relational
databases. AR allows to retrieve and manipulate data as objects (Obj Oriented way), not as static rows.
AR objects are ‘intelligent’, understand the structure of the table and know hot to Create, Read, Update and Delete rows.
Can be manipulated as objects, then saved easily.

Example:
user = User.new (var user to new instance of AR User class)
user.first_name = “Inge”
user.save # SQL INSERT row into DB
user.last_name = “Andr” # SQL UPDATE
user.delete # SQL DELETE row from DB

ActiveRelation
-——————-
Simplifies the generation of complex database queries as small
queries chainable one after another (like Ruby objects)
Manages complex joins and aggregations.
Queries do not execute until needed.
Heavily used by ActiveRecord.

Example:
users = User.where(:first_name => “Inge”)
users = users.order(“last_name ASC”).limit(5)
users = users.include(:articles_authored)

SELECT users., articles. FROM users LEFT JOIN artices ON (users.id = articles.author_id) WHERE users.first_name = “Inge” ORDER BY last_name ASC LIMIT 5 Finding Records -——————-
  • Primary key finder
    Subject.find(2) → expects it to exists, returns an object or an error
  • Dynamic finder
    Subject.find_by_id(2) → Returns null if not exists
  • Find all
    Subject.all → Returns an array of objects

Query Methods: Conditions
-———————————-
Returns an ActiveRelation object, which can be chained
ex: Subject.where(:visible => true).order(“position ASC”)

Condition expression types:

  • String:
    “name = ‘First’ AND visible = true”
    Flexible, raw SQL
    Use carefully and beware of SQL injection
    “name = ‘#{name}’ AND visible = true”
    name = “’ - hacker code -’”
  • Array: [“name = ? AND visible = ?”, “lol”, “true”]
    Flexible, escaped SQL, safe from SQL injecetion
  • Hash: {:name => “lol”, visible => true}
    Flexible, escaped SQL, safe from SQL injecetion
    Only supports equality, range, and subset checking
    No OR, LIKE, less than or greater than

Query Methods: Criteria
-——————————-

  • Order (sql_fragment): Order the results.
    – order sql format: table_name.column_name ASC/DESC.
    – table_name: Not necessary for a single table
    Recommended with joined tables
    Required when joined tables have the same column names
    Example: order(“subjects.created_at ASC”)
    order(“subjects.visible DESC, subjects.name ASC”)
  • Limit (ingeter): Limit the results to return
  • Offset(integer): Skip over records before selecting the results to return
Example: Subject.order(“subjects.position ASC”).limit(20).offset(40) – the order is not significant

Named Scopes
-—————
They are queries defined in a model defined using ActiveRelation query methods.
They can be called like ActiveRelation methods and can accept parameters.
In Rails 4 requies lambda syntax.

scope :with_content_type, lambda {|ctype|
where(:content_type => ctype)
}

Section.with_content_type(‘html’)

  1. Evaluated when called, not when defined
    scope :recent, lambda {
    where(:created_at => 1.week.ago..Time.now)
    }
  1. Chaining scopes
    Article.recent.visible.newest_first

Relational datbse associations
-——————————————

  • One-to-one
  • Onte-to-many
  • Many-to-many

Example: Imagine a school. Each classroom is asigned to a teacher. The teachers dont change
classrooms and teaches 4 classrooms per day.The students changes classrooms as they
move from course to course.

  • One-to-one (1:1): – A classroom “has_one” teacher.
    – A teacher is assigned (“belongs_to”) a classroom.
    – Foreign key allways goes to the “belongs_to” side (teachers table).
    + Classroom has_one :teacher.
    + Teacher belongs_to :classroom.
  • One-to-many (1:m): – A teacher “has_many” courses.
    – A course “belongs_to” a teacher.
    – FK goes on courses table.
    + Teacher has_many :courses.
    + Course belongs_to :teacher.
  • Many-to-many (m:n): – A course “has_many” students and also “belongs_to” many students.
    – A student “has_many” courses and also “belongs_to” many courses.
    – Two FK, they go in a join table.
    + Course has_and_belongs_to_many :students.
    + Student has_and_belongs_to_many :courses.
    (When the join is simple, using only the FK)

Join Table Naming Convention:
– first_table + _ + second_table
– Both table names are plural
– Alphabetical order
ex: Project – Collaborators => collaborators_projects
BlogPost – Category => blog_posts_categories

Controllers and CRUD Strong Parameters
-——————————————————
params.permit(:first_name, :last_name)
params.require(:subject)
params.require(:subject).params.permit(:first_name, :last_name)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment