Skip to content

Latest commit

 

History

History
153 lines (127 loc) · 2.72 KB

ruby-on-rails.md

File metadata and controls

153 lines (127 loc) · 2.72 KB

Ruby On Rails

Basics

  • Generate Ruby On Rails app
rails new MessengerApp
  • Download dependencies
bundle install
  • Start app
rails server

Create model

  • Generate model
rails generate model Message
  • Make changes to DB, edit db/migrate/
class CreateMessages < ActiveRecord::Migration
  def change
    create_table :messages do |t|
	  t.text :content
      t.timestamps #include created_at and updated_at
    end
  end
end
  • Update the database with the new messages data model
rake db:migrate
  • Seed the database with sample data from db/seeds.rb
m1 = Message.create(content: "We're at the beach so you should meet us here! I make a mean sandcastle. :)")

m2 = Message.create(content: "Let's meet there!")
rake db:seed
  • Generate controller
generate controller Messages

Add view action

  • Create new route and map it to a controller's index action, edit config/routes.rb
Rails.application.routes.draw do
  get 'messages' => 'messages#index'
end

Map default routes (index, show, new, create, edit, update and destroy)

resources :messages

Restrict default routes

resources :messages, only: [:index, :show]
  • Add action to Messages controller in app/controllers
class MessagesController < ApplicationController
    def index
      @messages = Message.all
    end
end
  • Update view, edit app/views/messages/index.html.erb
<% @messages.each do |message| %>
<div class="message">
    <p class="content"><%= message.content %></p>
    <p class="time"><%= message.created_at %></p>
</div>
<% end %>

Add create actions

  • Add route, edit config/routes.rb
Rails.application.routes.draw do
  get 'messages' => 'messages#index'
  get 'messages/new' => 'messages#new'
  post 'messages' => 'messages#create'
end
  • Add action, edit app/controllers/messages_controller.rb
class MessagesController < ApplicationController
    def index
      @messages = Message.all
    end

    def new
      @message = Message.new
    end

    def create
      @message = Message.new(message_params)
      if @message.save
        redirect_to '/messages'
      else
        render 'new'
      end
    end

    private
    def message_params
        params.require(:message).permit(:content)
    end
end
  • Add view, edit app/views/messages/new.html.erb
<%= form_for(@message) do |f| %>  
  <div class="field">
    <%= f.label :message %><br>
    <%= f.text_area :content %>
  </div>
  <div class="actions">
    <%= f.submit "Create" %>
  </div>
<% end %>
  • Add link, edit app/views/messages/index.html.erb
<%= link_to 'New Message', "messages/new" %>
<% end %>