Skip to content

Instantly share code, notes, and snippets.

@Jiggins
Created February 25, 2016 22:05
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 Jiggins/2405d72c9f6bc8466799 to your computer and use it in GitHub Desktop.
Save Jiggins/2405d72c9f6bc8466799 to your computer and use it in GitHub Desktop.

Rails

Getting Started

rails new Dema
bundle install

rails server

  • Show terminal during GET request
  • Leave running on another desktop

Important Files

File use
Gemfile Shows what gems need to be loaded to run the application
config/environments/* Environment specific variables for the development, test and production environments
config/routes.rb Associates each route with an action
config/secrets.yml YAML file containing things like private keys and api keys
db/schema Stores the database schema, should not be edited
db/migrations/* Scripts to migrate the database, i.e. add, modify or remove tables

app Directory Layout

Directory use
assets images, javascripts, stylesheets, etc.
controllers Classes used to define actions for routes
helpers utility classes, usually to help the view and controller
models Database objects
views Page layout written in eruby

MVC

Model (ActiveRecord)

  • Contains data for the application (often linked to a database)
  • Contains state of the application (e.g. what orders a customer has)

View (ActionView)

  • Presentation of data
  • Generates the user interface which presents data to the user
  • Does not do any additional work

Controller (ActionController)

  • Directs traffic
  • Receive events from the outside world (usually through views)
  • Interact with the model
  • Displays the appropriate view to the user

Model

rails generate scaffold user name:string email:string student_number:integer

See what it generates

less db/schema.rb
less db/migrations/

Run sql

rails db
.tables
.schema users
select * from users;

open rails console

User.create(name: 'Conor Loney', email: 'thescratchguy@scratch.mit.edu', student_number: 12)

conor = User.find_by name: 'Conor Loney'
conor.name

conor.update student_number: 2

Ruby Syntax

def hello_world
  puts("Hello, World!")
  puts "Hello, World!"
end

xs = [1,2,3]
xs.map do |x|
  x = x + 1
  x = x * x
end

xs.map {|x| x = x * x}

Controllers

rails generate controller pizza

vi app/controllers/pizza_controller.rb

# app/controllers/pizza_controller.rb 
class PizzaController < ApplicationController
    def index

    end
end

# app/views/pizza/index.html.erb
<h1>Pizza</h1>

<h3><%= link_to 'Just Eat', 'ttp://www.just-eat.ie' %></h3>

Views

Template Engine

app/views/application.html.erb

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