0% found this document useful (0 votes)
6 views

Rails

The document provides an introduction and overview of key concepts for Ruby on Rails. It discusses generating models and controllers, setting up routes, running tests, adding authentication, and more. Code examples are provided throughout to demonstrate how to structure a basic Rails application.

Uploaded by

Hajar Berahou
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Rails

The document provides an introduction and overview of key concepts for Ruby on Rails. It discusses generating models and controllers, setting up routes, running tests, adding authentication, and more. Code examples are provided throughout to demonstrate how to structure a basic Rails application.

Uploaded by

Hajar Berahou
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

rails

ruby beginner’s guide

seance 1
rails new myApp

in application_controller.rb

class ApplicationController < ActionController::Base


def bonjour
render html: "Bonjour tout le monde!"
end
end

in config/routes.rb

Rails.application.routes.draw do
get "up" => "rails/health#show", as: :rails_health_check

root "application#bonjour" # this is what we add


end

in bash

rails generate scaffold Auteur nom:string prenom:string

# generates views and models

rails db:migrate

# executes the migration in the database, you can see a schema.rb file creating itself

do the same for livres


and then run the server and go to /auteurs and /livres routes
db file can be found in storage

seance 2
creer un controlleur Pages avec 2 actions home et aide (/pages/home and /pages/aide to view them)

rails generate controller Pages home aide

les fichiers de tests sont dans test/controllers, to use those tests, il nous faut une bd de test

rails db:migrate RAILS_ENV=test


# to create the test db

rails test # lancer le test

when developing, we start with tests, and then we develop

rails 1
# we add this in test/controllers
test "should get contact" do
get pages_contact_url
assert_response :success
end

# how to make this test work?

# in config/routes.rb, we add:
get 'pages/contact'

# when we run the test again, no error, but there is a failure, there is no contact action in
controller

# in pages_controller.rb, we add
def contact
end

# still it'll tell us that there is no view


touch app/views/pages/contact.html.erb # add sth to it, and then the test will work

something about bootstrap


https://github.com/twbs/bootstrap-sass

# write the imports in custom.scss


# modify application.css to application.scss

# create views/layouts/_navigation.html.erb
https://getbootstrap.com/docs/3.3/components/#navbar
# copy whatever's in there in this file

# add this line to appllication.html.erb


<body>
<%= render 'layouts/navigation'%>
<%= yield %>
</body>

# then you can see this in /pages/*, it basically creates the navigation bar for all of the
pages

some css customization by modifying in custom.scss


we modify how the routing is done

# in routes.rb

# replace this
get 'pages/home'
get 'pages/aide'
get 'pages/contact'

# with this
root 'pages#home'
get 'aide' => 'pages#aide' # go to pages controller and run aide action
get 'contact' => 'pages#contact'

# now you need to use these to see aide

rails 2
aide_path => '/aide'
aide_url => 'http://localhost:3000/aide'

# when linking the pages, use this


<li><%= link_to "Contact", contact_path %></li>
<li><%= link_to "Aide", aide_path %></li>

# with this new config, even if you change the path to contact and aide, the controller will
still be able to find it, contrary to when you hard code it

put an image in assets and then link it through assets_url in scss

then we do this

rails generate model Utilisateur nom:string email:string


rails db:migrate
rails generate controller Utilisateurs new

# go to utilisateurs_controller_test.rb

# add this, which will create the user we'll work with

def setup
@utilisateur = Utilisateur.new(nom:"Bugs Bunny", email: "[email protected]")
end

test "nom doit etre present" do


@utilisateur.nom = ""
assert_not @utilisateur.valid?
end

rails db:migrate RAILS_ENV=test # again

seance 3
rails generate migration add_password_digest_to_utilisateurs password_digest:string

rails db:migrate

seance 4
note to self: look up how to make flash works

# in console
rails generate controller Session new

# in routes.rb, add
get 'login' => 'session#new'
get 'login' => 'session#create'
get 'logout' => 'session#destroy'

# replace the contents of views/session/new.html.erb with this


<h1>Identification</h1>
<%= form_for(:session, url: login_path) do |f| %>
<%= f.label :email %>
<%= f.email_field :email %>

rails 3
<%= f.label :password %>
<%= f.password_field :password %>

<%= f.submit "Se connecter", class: "btn btn-primary"%>


<% end %>

#in session controller add


def create
utilisateur = Utilisateur.find_by(
email: params[:session][:email].downcase
)

if utilisateur && utilisateur.authenticate(params[:session][:password])


log_in utilisateur # this is a fun we add in SessionHelper
redirect_to utilisateur
else
flash[:danger] = 'Combination Email/MDP invalide'
render 'new'
end
end

# go to app/helpers/session_helper.rb and add


module SessionHelper
def log_in(utilisateur)
session[:utilisateur_id] = utilisateur.id
end
end

# go to application_controller.rb, add
class ApplicationController < ActionController::Base
include SessionHelper
end
# so that sessionHelper can be available for all the other pages in the app

# in app/views/layouts/application.html.erb, add to the head:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

<script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>

<link rel="stylesheet" type="text/css"


href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">

# go to app/views/layouts/_navigation.html.erb
# replace this
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspo
pup="true" aria-expanded="false">Dropdown <span class="caret"></span></a>
<ul class="dropdown-menu">
<li><a href="#">Action</a></li>
<li><a href="#">Another action</a></li>
<li><a href="#">Something else here</a></li>
<li role="separator" class="divider"></li>
<li><a href="#">Separated link</a></li>

rails 4
</ul>
</li>
# with this:
<% if logged_in? %>
<li><%= link_to "Utilisateurs", '#' %></li>
<li class="dropdown">
<a href="#"
class="dropdown-toggle" data-toggle="dropdown"
role="button" aria-haspopup="true"
aria-expanded="false">Compte <span class="caret"></span></a>
<ul class="dropdown-menu">
<li><%= link_to "Profile", utilisateur_path(utilisateur_courant) %></li>
<li><%= link_to "Paramètres", '#' %></li>
<li role="separator" class="divider"></li>
<li><%= link_to"Se déconnecter", logout_path, method: "get"%></li>
</ul>
</li>
<% else %>
<li><%= link_to "Se connecter", login_path %></li>
<% end %>

# in app/helpers/session_helper.rb add:
def utilisateur_courant
@utilisateur_courant = @utilisateur_courant || Utilisateur.find_by(id: session[:utilisate
ur_id])
end

def logged_in?
! utilisateur_courant.nil?
end

# go back to session controller, add:


def destroy
log_out
redirect_to root_url
end

# once again, go to the session_helper.rb, add


def log_out(utilisateur)
session.delete(:utilisateur_id)
@utilisateur_courant = nil
end

#create file app/views/utilisateurs/edit.html.erb, copy the contents of show.html.erb into


it
# in session controller add
def edit
@utilisateur = Utilisateur.find(params[:id])
end

# go to /utilisateurs/[:id]/edit to see the results

# back in _navigateur.html.erb, replace this


<li><%= link_to "Paramètres", '#' %></li>
# with this:
<li><%= link_to "Paramètres", edit_utilisateur_path(utilisateur_courant) %></li>

rails 5
# in session controller add
def update
@utilisateur = Utilisateur.find(params[:id])
if @utilisateur.update(utilisateur_params)
flash[:success] = "profile actualisé!"
redirect_to @utilisateur
else
render 'edit'
end
end

# to ensure that a user is authenticated before updating


# go to utilisateur controller, add this before all the other actions
before_action :authenticate, :only => [:edit, :update]

# then add this as a private method


def authenticate
unless logged_in?
flash[:danger] = "Merci de se connecter."
redirect_to login_url
end
end

# try to access /utilisateurs/[:id]/edit without being logged in, you'll get an error msg

# to ensure that a user only gets to edit their own profile


# in utilisateur controller, add
before_action :bon_utilisateur, only: [:edit, :update]

# and this private method


def bon_utilisateur
@utilisateur = Utilisateur.find(params[:id])
redirect_to(root_url) unless @utilisateur == @utilisateur_courant
end

we want to display all the users now

# add this to utilisateur controller


def index
@utilisateurs = Utilisateur.all
end

# and add this action to the before_action line


before_action :authenticate, :only => [:edit, :update, :index]

# create app/views/utilisateurs/index.html.erb
# in the file, write
<h1>Tous les utilisateurs</h1>

<ul class="utilisateurs">
<% @utilisateurs.each do |utilisateur| %>
<li>
<%= link_to utilisateur.nom, utilisateur %>
</li>
<% end %>

rails 6
</ul>

# go back to _navigation.html.erb, find this line and modify it like this


<li><%= link_to "Utilisateurs", utilisateurs_path %></li>

# add these gems to the gemfile


gem 'will_paginate', '3.3.0'
gem 'bootstrap-will_paginate', '1.0.0'

# in the bottom of index.html.erb, add this


<%= will_paginate %>

# go back to utilisateur, modify the index action


def index
@utilisateurs = Utilisateur.paginate(
:page => params[:page], :per_page => 2
)
end

creating an admin user, we’ll add a column to the user table in our db to specify whether it’s an admin or not

# in the cli
rails generate migration add_admin_to_utilisateurs admin:boolean

# go to db/migrate/<timestamp>_add_admin_to_utilisateurs.rb, add the last hash to the add col


umn line
dd_column :utilisateurs, :admin, :boolean, :default => false
# this simply makes sure that a user is not an admin by default

# then in the cli


rails db:migrate

# open the rails console and create a user admin


Utilisateur.create(nom:"admin", email:"[email protected]", password:"password", password_con
firmation:"password", admin:true)

# go to user controller, add this action


def destroy
Utilisateur.find(params[:id]).destroy
flash[:success] = "Utilisateur supprimé"
redirect_to root_url
end

# add this line at the top


before_action :utilisateur_admin, only: destroy
# this ensures that before destroying, we invoke the utilisateur_admin method, which will c
heck whether a user is an admin ig

# and add the destroy method in this line


before_action :authenticate, :only => [:edit, :update, :index, :destroy]

# then add this method with the other private ones


def utilisateur_admin
@utilisateur = Utilisateur.find(params[:id])
if not @utilisateur_courant.admin? || @utilisateur == @utilisateur_courant

rails 7
redirect_to(root_url)
end
end
# this ensures it is an admin destroying a user, and if it's normal user, then they're dest
roying their own account

# in index.html.erb

# find this line


<%= link_to utilisateur.nom, utilisateur %>

# add under it

<% if @utilisateur_courant.admin? || utilisateur == @utilisateur_courant %>


<%= link_to "delete", utilisateur, data: {
turbo_method: :delete,
turbo_confirm: "Are you sure?"
} %>
<% end %>

# in console
rails generate model Article titre:string description:text utilisateur:references
rails db:migrate

# in models/Article.rb, add
validates :utilisateur_id, presence: true
validates :titre, presence:true, length: {maximum: 200}
validates :description, presence:true, length: {maximum: 20000}

# the in utilisateur model, add


has_many :articles, dependent: :destroy

# in consoles
rails generate controllers Articles

# dans la console, i wann kms, let us oUTTTTTTT


Article.create(titre:"titre 1", description: "description1 description2 description3", util
isateur_id:2)

# add app/views/articles/_article.html.erb, open it, and add

<li id="article-<%= article.id %>">


<span class="utilisateur"><%= link_to article.utilisateur.nom,
article.utilisateur %></span>
<span class="titre"><%= article.titre %></span>
<span class="timestamp">
Posté il y a <%= time_ago_in_words(article.created_at) %>.
</span>
</li>

# go back to utilisateur controller, modify the show action


def show
@utilisateur = Utilisateur.find(params[:id])
@articles = @utilisateur.articles
end

rails 8
# in show.html.erb of utilisateurs, add
<% if @utilisateur.articles.any? %>
<h3>Articles (<%= @utilisateur.articles.count %>)</h3>
<ol class="articles">
<%= render @articles %>
</ol>
<% end %>

# add the following line to routes.rb


resources :articles, only: [:create, :destroy]

# go to articles controller
def create
@article = utilisateur_courant.articles.build(article_params)
if @article.save
flash[:success] = "Article crée"
redirect_to root_url
else
redirect_to root_url
end
end

def destroy
end

private

def article_params
params.require(:article).permit(:titre, :description)
end

# add this to the articles controller too


before_action :authenticate, :only => [:create, :destroy]

# we already have the authenticate method in the users controller, if we want to reuse it, w
e'll have to move it to the application controller

now we want to modify home to display the article form if the user is connected, and display the og page if they’re not
connected

# replace home.html.erb with this


<% if logged_in? %>
<div class="row">
<aside class="col-md-4">
<section class="article_form">
<%= form_for(@article) do |f| %>

<div class="col-sm-8">
<%= f.text_field :titre, rows: 10, class: "form-control", placeholder: "Titre" %>
</div>
<div class="col-sm-8">
<%= f.text_area :description, rows: 10, class: "form-control", placeholder: "Texte"
%>
</div>
<%= f.submit "Soumettre", class: "btn btn-primary" %>
<% end %>
</section>

rails 9
</aside>
</div>
<% else %>

<div class="container">
<div class="jumbotron">
<h1>LE BLOG</h1>
<p>Un blog est un type de site web – ou une partie d'un site web – utilisé pour la publ
ication périodique et régulière d'articles, généralement succincts, et rendant compte d'une a
ctualité autour d'un sujet donné ou d'une profession. (<a href="https://fr.wikipedia.org/wik
i/Blog">Wikipedia</a>)</p&gt;
<!-- <p><a class="btn btn-primary btn-lg" href="#" role="button">S'inscrire</a></p> -->
<%= link_to "S'inscrire", inscription_path, class: "btn btn-lg btn-primary" %>
</div>
</div>

<% end %>

# modify the home action in pages controller


def home
@article = utilisateur_courant.articles.build if logged_in?
end

rails 10

You might also like