RailsBridgeTriangle

Rails & MVC

Why do we need organization?

  • Code grows over time
  • Code becomes unmanageable
  • Simple Scripts Grow From 100 Lines to 4000 Lines

We need organization!

  • Convention over configuration
  • One less decision for you to make
  • Allows you to work with other teams very easily
  • A place for everything and everything in its place.

MVC The Rails Way

  • Model
  • View
  • Controller

Models

  • Represent "things" in our application
  • Usually stored in the database
  • Live in `app/models`

Model Example - Twitter

  • What things do we need in a twitter application?
  • Tweet
    • Text
    • user
  • User
    • Username
    • Password

Tweet Model


class Tweet < ActiveRecord::Base
  belongs_to :user
end
          

User Model


class User < ActiveRecord::Base
  has_many :tweets
  has_many :followers
  has_many :followed_users

  def recent_tweets
    tweets.where("created_at > ?", 2.weeks.ago)
  end
end
          

Views

  • Display our models!
  • Use HTML for browser rendering.
  • Used ERB to show anything from "code"
  • Live in `app/views`

Tweet View


Tweet from <%= @tweet.username %>

<%= @tweet.text %>

Combining Views

Controllers

  • Traffic Cops
  • Line up information and send it to the view

Example Controller

http://localhost:3000/tweets


class TweetsController < ApplicationController
  def index
    @tweets = Tweets.all
  end
end
          

The Flow

  • User visits a URL
  • Controller is activated; looks up the model
  • Controller passes the model to the view
  • View is rendered for the user to see

Recap

  • Models represent data in the real world
  • Views show your models
  • Controllers connect models to views

Have fun!