Skip to content

Instantly share code, notes, and snippets.

@dahngeek
Last active May 13, 2019 20:21
Show Gist options
  • Save dahngeek/c617b8707efbc876d019952a840ce0bd to your computer and use it in GitHub Desktop.
Save dahngeek/c617b8707efbc876d019952a840ce0bd to your computer and use it in GitHub Desktop.

Cheatsheet para Ruby on Rails 5 alt text

Hoja de trucos de Ruby on Rails 5

Manejo de gemsets

rvm gemset list
rvm gemset use

Reconocimiento del usuario en la terminal si da problemas: /bin/bash --login

Configurar detección automatica del gemset al entrar con la terminal a la carpeta EJEMPLO: tengo un gemset 'Progra3' o usa el que hayas creado sin comillas y guardalo en el archivo .ruby-gemset

echo progra3 > .ruby-gemset

Instalación

Ver si esta bien la versión de ruby: ruby --version Ver si esta bien sqlite: sqlite --version

  1. Instalar rails: gem install rails

  2. Crear nueva app de rails: rails new firstApp

  3. Instalar todos los paquetes necesrios: bundle install

  4. Ejecutar el servidor incluido rails s

Si da error por algo de javacript, en el Gemfile agregar/descomentar:

gem 'therubyracer' 
gem 'execjs'

o

sudo apt install nodejs npm
bundle install
rails s

Scaffolding y generadores de Rails

Scaffolding de modelos

rails g scaffold Car brand:string model:string year:integer
rails g scaffold Brand name:string country:string description:text foundation_year:integer

Eliminar un modelo

rails d model Car

Para usar una llave foranea (Relación one to many):

rails g scaffold Comment body:string author:string post:references

Y en el modelo padre (el que tiene one) se debe agregar:

has_many :comments

Otro ejemplo:

rails g scaffold Author name:string lastname:string bio:text
rails g scaffold Topic name:string description:text
rails g scaffold Book title:string description:text author:references topic:references

Controladores

rails g controller controller Vehicles list details
rails destroy controller Vehicles

Para hacer un index diferente como para agregar búsquedas en el listing:

@movies = Movie.all //Esto ya estaba
@movies = @movies.where('title like ?', '%' + params[:movie_title] + '%' ) if params[:movie_title]

Para evitar que salga error que sale cuando una llave foranea no existe:

# DELETE /units/1.json
  def destroy
    if @unit.pathfinders.any?
      # redirect back or whatever
      respond_to do |format|
        format.html { redirect_to units_url, notice: 'No se puede borrar porque tiene conquistadores' }
        format.json { head :no_content }
      end
    else
      @unit.destroy
      respond_to do |format|
        format.html { redirect_to units_url, notice: 'Unit was successfully destroyed.' }
        format.json { head :no_content }
      end
    end
  end

Migraciones

Eliminar una columna:

rails g migration RemoveDescriptionFromCar

o rais g migration RemoveThemeFromBook theme_id:integer

Agregar columna

rails generate migration add_pages_to_books pages:integer
rails db:migrate

Crear tabla de relacion many-to-many:

rails g migration CreateJoinTableBookTheme books themes

Para completar la relación Many-to-many, en los modelos involucrados (acá books o themes):

//Para themes
has_and_belongs_to_many :books

//Para books
has_and_belongs_to_many :themes

Base de datos

Para crear la base de datos y ejecutar las últimas migraciones (Actualizar las tablas en base a las migraciónes creadas)

rake db:create
rails db:migrate

Para retroceder la base de datos:

rails db:rollback steps=3
rails db:migrate version=0

En caso de que generate se quede colgado o trabado usar el comando rake app:update:bin ( para ruby mayor a 5) https://stackoverflow.com/questions/31857365/rails-generate-commands-hang-when-trying-to-create-a-model

Vistas

Variables dentro de comillas

href="#{@book.author.name}"

Rutas / Links

En general se vería así:

<%= link_to 'My Link', blogs_path %>

urls con link modelo_path o modelo_url: books_path

con parametros ?theme_id=theme.id: books_path(:theme_id => theme.id)

Esto lo recibe el index del controlador. Se pueden recibir los paramtros asi: params[:theme_id]

Y se puede filtrar habiendo recibido ese parametro de la siguiente manera (esto es el método index):

Consulta filtrada

@books = Book.all #Esto ya estaba
@books = @books.where(:theme_id => params[:theme_id]) if params[:theme_id] #lo filtra solo si lo recibió al parametro theme_id.

Cambiar el home o el root de la pagina Para que no sea la pagina de bienvenida sino alguna otra de los listados que hacemos en el archivo config/routes.rb dentro del Rails.application.routes.draw do:

root :to => "municipalities#index"

Formularios

Definir el formuario <%= from_with(model:book, local:true) do |form| %>

<%= form.label :title %>
<%= form.TIPODE :title %>
TIPODE = number_field, text_field...

Listas o selectores en los formularios

Selector:

<%= collection_select(:book, :author_id, Author.all, :id, :full_name) %>

Checkboxes:

<%= collection_check_boxes(:book, :topic_ids, Topic.all, :id, :name) do |b|
      b.label(:"data-value" => b.value) {b.check_box + b.text}  
end
%>

No olviar agregar al controller (en este caso books_controler) En los parámetros books_params, agregar en el permit el campo :topic_ids en el caso de book

{:topic_ids => []})

Ver ejemplo: https://github.com/dahngeek/rails-biblioteca/commit/6092aa3332ed276decf889d8e4479514de20737b

Modelos

VALIDACIONES

Email/Correo electronico:

validates_format_of :mail, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i

Relacion uno a uno (has_one)

validates_uniqueness_of :mayor_id

ver validaciones en el link: https://gist.github.com/rstacruz/1569572

Más links útiles

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