Ruby on Rails

Partie 3 : Ajouter des composantes

https://slides.com/sophiedeziel/ruby-on-rails-milestone-3

Ajouter un gem

Bundler: gem pour gérer les dépendances

Gemfile: Fichier dans votre projet pour spécifier les dépendances

Rubygems.org: Repository de gems

Ruby toolbox: Outil très pratique pour évaluer un gem

Devise

  • Gem très utilisé pour l'authentification dans Rails
  • Rails engine
  • Très bien maintenu
  • "Facile" à utiliser

Devise

source 'https://rubygems.org'

gem 'rails', '4.2.4'
gem 'pg'
gem 'sass-rails', '~> 5.0'
gem 'uglifier', '>= 1.3.0'
gem 'coffee-rails', '~> 4.1.0'
gem 'jquery-rails'
gem 'turbolinks'
gem 'jbuilder', '~> 2.0'
gem 'sdoc', '~> 0.4.0', group: :doc

gem 'devise'

group :development, :test do
  gem 'byebug'
end

group :development do
  gem 'web-console', '~> 2.0'
  gem 'spring'
end

Gemfile

Devise

bundle install

Devise

rails generate devise:install

rails generate devise user

rake db:migrate

Devise

Rails.application.configure do
  # Many other default config are here

  config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }
end

config/environments/development.rb

Quand on change un initializer, il faut redémarer le serveur
(ctrl+c et ensuite rails server)

Devise

class PostsController < ApplicationController
  before_action :authenticate_user!
  before_action :set_post, only: [:show, :edit, :update, :destroy]

  # GET /posts
  # GET /posts.json
  def index
    @posts = Post.all
  end

  # GET /posts/1
  # GET /posts/1.json
  def show
  end

  # GET /posts/new
  def new
    @post = Post.new
  end

  # GET /posts/1/edit
  def edit
  end

  # POST /posts
  # POST /posts.json
  def create
    @post = Post.new(post_params)

    respond_to do |format|
      if @post.save
        format.html { redirect_to @post, notice: 'Post was successfully created.' }
        format.json { render :show, status: :created, location: @post }
      else
        format.html { render :new }
        format.json { render json: @post.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /posts/1
  # PATCH/PUT /posts/1.json
  def update
    respond_to do |format|
      if @post.update(post_params)
        format.html { redirect_to @post, notice: 'Post was successfully updated.' }
        format.json { render :show, status: :ok, location: @post }
      else
        format.html { render :edit }
        format.json { render json: @post.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /posts/1
  # DELETE /posts/1.json
  def destroy
    @post.destroy
    respond_to do |format|
      format.html { redirect_to posts_url, notice: 'Post was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_post
      @post = Post.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def post_params
      params.require(:post).permit(:title, :content)
    end
end

app/controllers/posts_controller.rb

Associations de models

Associer un 'user' à un 'post' comme auteur

rails g migration add_author_id_to_posts author_id:integer

rake db:migrate
class Post < ActiveRecord::Base
  belongs_to :author, class_name: 'User'
end

app/models/post.rb

class User < ActiveRecord::Base
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  has_many :posts
end

app/models/user.rb

  # POST /posts
  # POST /posts.json
  def create
    @post = Post.new(post_params)

    @post.author = current_user

    respond_to do |format|
      if @post.save
        format.html { redirect_to @post, notice: 'Post was successfully created.' }
        format.json { render :show, status: :created, location: @post }
      else
        format.html { render :new }
        format.json { render json: @post.errors, status: :unprocessable_entity }
      end
    end
  end

app/controllers/posts_controller.rb

   <% @posts.each do |post| %>
      <tr>
        <td><%= post.title %></td>
        <td><%= post.author %></td>
        <td><%= link_to 'Show', post %></td>
        <td><%= link_to 'Edit', edit_post_path(post) %></td>
        <td><%= link_to 'Destroy', post, method: :delete, data: { confirm: 'Are you sure?' } %></td>
      </tr>
    <% end %>

app/views/posts/index.html.erb

   <% @posts.each do |post| %>
      <tr>
        <td><%= post.title %></td>
        <td><%= post.author.name %></td>
        <td><%= link_to 'Show', post %></td>
        <td><%= link_to 'Edit', edit_post_path(post) %></td>
        <td><%= link_to 'Destroy', post, method: :delete, data: { confirm: 'Are you sure?' } %></td>
      </tr>
    <% end %>

app/views/posts/index.html.erb

rails generate migration add_name_to_users name

rake db:migrate

OH NOES!!!!!!

Rails console

rails console

Running via Spring preloader in process 66100
Loading development environment (Rails 4.2.4)
2.2.1 :001 > User.first
  User Load (0.2ms)  SELECT  "users".* FROM "users"  ORDER BY "users"."id" ASC LIMIT 1
 => #<User id: 1, email: "courrier@sophiedeziel.com", encrypted_password: "$2a$10$0dgMAquNLDson7vBuW31ZO7tEtnpXO5azrJK7Lymjoy...", reset_password_token: nil, reset_password_sent_at: nil, remember_created_at: nil, sign_in_count: 1, current_sign_in_at: "2016-04-21 23:44:21", last_sign_in_at: "2016-04-21 23:44:21", current_sign_in_ip: "69.165.212.230", last_sign_in_ip: "69.165.212.230", created_at: "2016-04-21 23:44:21", updated_at: "2016-04-21 23:44:21", name: nil> 
2.2.1 :002 > User.first.update_attributes(name: "Sophie Déziel")
   (0.1ms)  begin transaction
  SQL (0.4ms)  UPDATE "users" SET "name" = ?, "updated_at" = ? WHERE "users"."id" = ?  [["name", "Sophie Déziel"], ["updated_at", "2016-04-22 00:21:43.047705"], ["id", 1]]
   (1.4ms)  commit transaction
 => true 
2.2.1 :003 > Post.where(author: nil)
  Post Load (0.2ms)  SELECT "posts".* FROM "posts" WHERE "posts"."author_id" IS NULL
 => #<ActiveRecord::Relation [#<Post id: 1, title: "Titre de blog", content: "<p>Dolor quinoa placeat exercitation labore. Kale ...", created_at: "2016-04-21 00:54:40", updated_at: "2016-04-21 01:30:34", author_id: nil>]> 
2.2.1 :004 > Post.where(author: nil).update_all(author_id: 1)
  SQL (2.1ms)  UPDATE "posts" SET "author_id" = 1 WHERE "posts"."author_id" IS NULL
 => 1 
<% @posts.each do |post| %>
  <article>
    <h2><%= post.title %></h2>
    <div class='post-meta'>
      By: <%= post.author.name  %><br/>
      Last updated: <%= post.created_at.to_s(:long) %>
    </div>

    <div class='post-content'>
      <%= simple_format post.content  %>
    </div>
  </article>
<% end %>

app/views/home/index.html.erb

Validations

class Post < ActiveRecord::Base
  belongs_to :author, class_name: 'User'

  validates_presence_of :title, :content, :author
end

app/models/post.rb

Brouillons

  • N'afficher que les posts publiés sur le home
  • Permettre la création de posts vides
  • Voir tous les posts dans l'administration
rails g migration add_published_to_posts published:boolean
class AddPublishedToPosts < ActiveRecord::Migration
  def change
    add_column :posts, :published, :boolean, default: false
  end
end
rake db:migrate
class Post < ActiveRecord::Base
  belongs_to :author, class_name: 'User'

  validates_presence_of :title, :content, :author

  scope :published, -> { where(published: true) }
end

app/models/post.rb

class HomeController < ApplicationController
  def index
    @posts = Post.published.limit(20)
  end
end

app/controllers/posts_controller.rb

  <div class="field">
    <%= f.label :title %><br>
    <%= f.text_field :title %>
  </div>
  <div class="field">
    <%= f.label :content %><br>
    <%= f.text_area :content %>
  </div>
  <div class="field">
    <%= f.label :published %><br>
    <%= f.check_box :published %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>

app/views/posts/_form.html.erb

   private
    # Use callbacks to share common setup or constraints between actions.
    def set_post
      @post = Post.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def post_params
      params.require(:post).permit(:title, :content, :published)
    end

app/controllers/posts_controller.rb

class Post < ActiveRecord::Base
  belongs_to :author, class_name: 'User'

  validates_presence_of :title, :author
  validates_presence_of :content, if: :published?

  scope :published, -> { where(published: true) }
end

app/models/post.rb

On déploie?

🎉

Heroku

  • Plan gratuit
  • Déploiements faciles
  • Nombreux plugins

group: :production do
  gem 'rails_12factor'
end

ruby '2.2.4'

Ajouter au Gemfile

Et bundle install

Déploiement par Git

git init

git add .

git commit -m "initial commit"

heroku create

git push heroku master

https://toolbelt.heroku.com/

Optionnellement, mais fortement recommandé:

Pousser à Github aussi (et éditer le Readme.md

heroku run rake db:migrate

Voilà!!

Milestone 3 atteint!

Ruby on Rails Milestone 3

By Sophie Déziel

Ruby on Rails Milestone 3

  • 1,867