Sei sulla pagina 1di 4

RENDER

Rails per mandare la pagina al browser deve assemblare partial,template e layout


Ogni controller ha un proprio Layout , e dei template disponibile (cosi come anche i
partial)
Se il layout non viene specificato nel controller , allora viene usato quello di default , che
sarebbe application.html.erb. Lo yield del layout serve per andare ad inserire il contenuto
del template della action.
Di base , quando creiamo un controller abbiamo alcuni metodi senza comandi.
Per esempio , possiamo avere in un generico controller la seguente action view:
# GET /carts/1
# GET /carts/1.json
def show
end
Come vediamo non presente NULLA nel metodo show
Quindi , come possibile che quando ci colleghiamo a localhost:3000/carts/show/1
Siamo in grado di vedere il carrello con ID pari a 1?
In pratica, Rails fara' AUTOMATICAMENTE il rendering della view con il nome della action
del controller che vogliamo richiamare
(Rails will automatically look for the action_name.html.erb template in the controller's
view path and render it.)
Per cambiare il comportamento di base di rendering di Rails possiamo usare il metodo
render.
Per esempio:
def update
@book = Book.find(params[:id])
if @book.update(book_params)
redirect_to(@book)
else
render "edit"
end
end
Se l'update fallisce chiamiamo la view edit.html.erb
(Possiamo anche usare un simbolo , se lo preferiamo. Es: render :edit)
Con il metodo render , inoltre , possiamo eseguire il rendering delle collections. Quando
passiamo a render una collection, questo applica per ogni membro della collection un
template parziale.
render(@cart.line_items)

Il template parziale deve trovarsi di default nella stessa directory dell'oggetto prodotto.
Inoltre , il parziale deve iniziare con un underscore '_' . Nei parziali sono disponibili le
variabili di istanza che condividono controller e view.Un parziale puo' richiamare al suo
interno un altro parziale!

Rules to remember:
redirect_to()
Does a full page redirect sending a 302 html code
All variables will be lost
Sends a new request to the system
render()
Sends a 200 html code response
Holds the state of variables
The action is not executed, only the view is rendered
Bisogna fare molta attenzione a quando dentro una action si esegue un render. Perch
rimaniamo ancora in quella action , poich il render carica solo la view ma non comincia
una nuova richiesta. Quindi se lutente fa un Aggiorna dal browser, inviando
nuovamente i dati , possono esserci problemi. Meglio fare una redirect_to per fare in
modo che venga creata una nuova richiesta della action richiesta.

<%= yield%>
.
First of all, yield is ruby, render is rails
Without any arguments, yield will render the template of the current controller/action. So
if you're on the cars/show page, it will render views/carts/show.html.erb.
Calling content_for stores a block of markup in an identifier for later use.
<% content_for :head do %>
<title>A simple page</title>
<% end %>
<p>Hello, Rails!</p>

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

</body>
</html>

The result of rendering this page into the supplied layout would be this HTML:
<html>
<head>
<title>A simple page</title>
</head>
<body>
<p>Hello, Rails!</p>
</body>
</html>

ROUTING
Action pack il CUORE delle applicazioni Rails. LAction Pack si basa su Action Controller ,
Action Dispatch e Action View. Action Dispatch indirizza le richieste al controller; Action
Controller converte le richieste in risposte; Action View usato da Action Controller per
formattare queste risposte.
Per sapere cosa fare con una richiesta in arrivo , Rails in base a coincidenze con pattern ,
richieste e condizioni riesce a mappare gli URL su una azione. Lidea che sta dietro a Rest
stata formalizzata da Roy Fielding nella sua tesi di dottorato. Laspetto positivo delle
linee base di Rest che si ha una interfaccia semplice e soprattutto standard per potere
accedere alle varie risorse. I metodi di http forniscono questa interfaccia standardizzata.
Molte delle route hanno un nome , e ci consentono di utilizzare funzioni helper.
Rest permette inoltre di separare la presentazione dei dati dal suo contenuto. Che vuol
dire? Che se arriva una richiesta da una applicazione , piuttosto che da un browser web ,
allora i dati saranno presentati un un formato apposito: per esempio Json. Come fa Rails a
capire chi sta richiedendo i dati? Tramite lHeader della request http. (Accept: .). Oppure
possiamo specificare il format nell URL.
resources :photos
creates seven different routes in your application, all mapping to the Photos controller:
Resource routing allows you to quickly declare all of the common routes for a given
resourceful controller. Instead of declaring separate routes for your index, show, new,
edit, create, update and destroy actions, a resourceful route declares them in a single line
of code.
new_controllername_path
edit_controllername_path
controllername_path

returns /controllername/new
returns /controllername/edit
returns /controllername

As with plural resources, the same helpers ending in _url will also include the host, port
and path prefix.
Path and URL Helpers
Creating a resourceful route will also expose a number of helpers to the controllers in
your application. In the case of resources :photos:
photos_path
returns /photos
new_photo_path
returns /photos/new
edit_photo_path(:id)
returns /photos/:id/edit
(for instance, edit_photo_path(10) returns /photos/10/edit)
photo_path(:id)
returns /photos/:id
(for instance, photo_path(10)
returns /photos/10)
Each of these helpers has a corresponding _url helper (such as photos_url) which returns
the same path prefixed with the current host, port and path prefix.
redirect_to @article:
Conversely, as Rails is object / resource orientated, every method / function you run is
based around resources, so this is just an extension of this idea.
When you use the likes of redirect_to or render with an object, Rails can take the object &
pull down the corresponding routes for it.
Basically, if you have an @article object, Rails will observe that it's built from the Article
model, and will consequently look for the Articles controller & the show method, to show
a single resource on the page.
-

Potrebbero piacerti anche