Skip to content

Instantly share code, notes, and snippets.

@WallasFaria
Last active August 12, 2019 21:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save WallasFaria/0894106bc75783f9ab158520d7913025 to your computer and use it in GitHub Desktop.
Save WallasFaria/0894106bc75783f9ab158520d7913025 to your computer and use it in GitHub Desktop.

Model

criar:

rails g model NomeDoModel

Validar:

presença de um campo:

validates presence: true

Consultar

por id

NomeDoModel.find 1

por outros campos

NomeDoModel.find_by nome_do_campo: 'valor'

lista de todos

NomeDoModel.all

lista com where

NomeDoModel.where(nome_do_campo: 'valor')
NomeDoModel.where('nome_do_campo = ?', 'valor')

lista com like

NomeDoModel.where('nome_do_campo like ?', 'valor%')

Controller

Renderiar

Formato HTML

Se um formato específico não for passado o rails responde no formato HTML, renderizando o arquivo com mesmo nome do método onde foi chamado, na pasta de mesmo nome do controller e atual dentro da pasta app/views.

Exemplo:

class ProductsController < ApplicationController
  def index
  end
end

vai renderizar o arquivo app/views/products/index.html.erb

também é possível especificar qual o nome do arquivo que deseja renderizar usando o método render.

class ProductsController < ApplicationController
  def index
    render 'list_all'
  end
end

vai renderizar o arquivo app/views/products/list_all.html.erb

outro recurso é passar o caminho completo, passando a pasta e o arquivo.

class ProductsController < ApplicationController
  def index
    render 'lists/products'
  end
end

vai renderizar o arquivo: app/views/lists/products.html.erb

Formato HTML Layouts

Outro comportamento padrão na renderização do formato HTML é a aplicação do layout ao arquivo que está sendo enderizado.

usando como base o exemplo anterior, ao renderizar o arquico app/views/products/index.html.erb, o rails lê o arquivo app/views/layouts/application.html.erb, e inclui o arquivo products/index.html.erb no lugar do yield do layout.

Exemplo:

arquivo: app/views/products/index.html.erb

<h1>Lista de Produtos</h1>

arquivo: app/views/layouts/application.html.erb

<!DOCTYPE html>
<html>
  <head>
    <title>Título</title>
  </head>

  <body>
    <%= yield %>
  </body>
</html>

resultado do arquivo renderizado:

<!DOCTYPE html>
<html>
  <head>
    <title>Título</title>
  </head>

  <body>
    <h1>Lista de Produtos</h1>
  </body>
</html>

Ao renderizar, podemos especificar qual layout queremos usar

def index
  render 'lists/products', layout: 'admin'
end

ou informar que queremos renderizar sem layout

def index
  render 'lists/products', layout: false
end

Formatos JSON, inline, js

Além do formatp HTML, podemos renderiar em outro fomatos

JSON:

def index
  render json: []
end

js:

def index
  render js: 'alert("oi")'
end

inline:

def index
  render inline: 'recurso foi salvo!'
end

Obs.: estes formatos não trabalham com layouts

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