You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesi贸n a prueba de IA

Antes: $249

Currency
$209
Suscr铆bete

Termina en:

2 D铆as
11 Hrs
39 Min
55 Seg

Agregar el primer conjunto de scaffolds

12/36
Resources

What is the Rails Scaffold and how does it benefit us?

The Scaffold in Ruby on Rails is a powerful tool that allows you to quickly create the basic structure of an MVC (Model, View, Controller) model for a web application. Facilitating the developer's work, this generator executes multiple tasks simultaneously, integrating models, routes, controllers and views, as well as asset resources when necessary.

How does Rails Generate Scaffold work?

Using the Rails Generate Scaffold command is an efficient method for establishing the basis of a resource in a Rails web application. Suppose you want to model the "Book" concept. You could run a command in the console like the following:

rails generate scaffold Book title:string author:string description:text isbn:string page_count:integer.

This command will create:

  • Model: it will manage the data logic for the books.
  • Migrations: it will generate the corresponding tables in the database.
  • Controller (BooksController): will manage the books actions, such as create, update, list and delete.
  • Views: visual representation of the data, allowing user interaction with the application.

What does Rails Generate Scaffold generate?

When we run the Scaffold, several generators are invoked simultaneously. Let's see each one of them:

  1. ActiveRecord Generator: creates the migration files for the databases, it is crucial to run these migrations to introduce changes to the database. This is achieved with the rails db:migrate command.

  2. Routes Generator: Establishes the routes for the resources used, using the resources method. This facilitates the access to the different HTTP methods (GET, POST, PATCH, DELETE) needed to interact with the resources.

  3. Scaffold Controller: Creates a specific controller to handle the actions related to the resource, for example, BooksController for books.

  4. Helper Generator: Provides abstractions to be reused in views, improving code organization.

  5. JBuilder: Generates JSON files, allowing to manage information efficiently and return responses in this format when required.

  6. Assets Generator: Creates styles through .scss files to customize the generated views.

How does the Scaffold support the flow of an application?

Once all the files are in place, we can run the application on a local server using rails server and access the resource through a browser. The URL localhost:3000/books displays a list of books and provides options to create, view, edit and delete books.

The flow follows this sequence:

  1. Request at the specific URL (e.g., /books).
  2. Router routes to BooksController.
  3. BooksController interacts with the model and the database to obtain the necessary data.
  4. Data is passed to a specific view, generated by the Scaffold.
  5. The view uses ERB to render the HTML that is presented to the user in the browser.

Practical tips when using Scaffold

  • Explore and customize: Although Rails Scaffold generates an initial structure, customizing controllers, models and views will allow you to adjust them to the specific needs of your application.
  • Understand migrations: Before running an application, be sure to perform all necessary migrations. This will allow the database to be in sync with the model.
  • Clean and efficient URLs: Use the Rails path generator to maintain semantic and efficient URLs. This is a good practice that makes the code easier to read and maintain.

Finally, don't stop! Keep exploring and learning about Rails and its tools, this will give you the confidence you need to develop robust and custom applications. Remember that each step brings you closer to becoming an expert in using Rails.

Contributions 15

Questions 1

Sort by:

Want to see more contributions, questions and answers from the community?

驴QU脡 ES SCAFFOLD?
Un conjunto de archivos generados autom谩ticamente que forman la estructura b谩sica de un proyecto de Rails. Permite crear una abstracci贸n de un elemento real. Estos incluyen:

  • Un controlador
  • Un modelo
  • Vistas para cada acci贸n est谩ndar del controlador (Index, edit, show, new, destroy)
  • Una ruta
  • Una migraci贸n para la base de datos

COMO USAR SCAFFOLD
Se necesita escribir rails g scaffold, el recurso y sus _atributos _ incluyendo el tipo de dato usando dos puntos ( : )

rails g scaffold _recurso_ atributos:string

Luego de usar el comando se generar谩 una serie de archivos. Todo lo que diga invoke har谩 referencia a un invocador. Algunos son:

  • active_record: Crea dos archivos para las migraciones
  • resource_route: Crea las rutas de nuestro elemento. Esto incluye controladores y acciones (ndex, edit, show, new, destroy)
  • scaffold_controller: Crea un controlador de nuestro recurso
  • helper: Crea abstracciones dentro de las vistas
  • jbuilder: Permite crear archivos de tipo JSON
  • assets / scss : Crea un archivo tipo SASS en la carpeta asstes para modificar estilos.

ACCEDER A NUESTRO RECURSO
Para acceder al recurso, asi como sus acciones debemos iniciar el servidor usando rails s. Una vez activado vamos al navegador y colocamos la url 127.0.0.1:3000/elemento.

  • Podemos ir a routes.rb para ver la configuraci贸n de esta acci贸n.
  • Para ir directo a la acci贸n del controlador del recurso usamos recurso_controller.rb. Aqui podemos ver varias funci贸nes correspondientes con cada vista (index, show, new, edit, destroy).
  • Para ver vista vamos a la carpeta Views.

Me encanta que el profesor explique de forma detallada cada cosa que sucede al ejecutar un comando con rails. Este curso es de 10 =)

Me sorprendi贸 mucho la posibilidad de crear un crud con una sola l铆nea de comando.

Buenisimo el video, estoy super ansioso por mas!

Con el siguiente comando pueden ver todas las rutas que tienen disponibles en su aplicaci贸n de Rails:

rails routes --expanded

Muy completa explicaci贸n

te hace un crud autom谩tica mente ?

En este punto es importante hablar de TurboLinks y como Ruby on Rails lo utiliza para optimizar la carga cuando salta de una vista a otra.

https://github.com/turbolinks/turbolinks

Commands we used:

rails g scaffold Book title:string author:string description:text isbn:string pages_count:integer
rails s
rails db:migrate

No me gusta mucho el scaffold pero bueno vamos por ello

Buen铆simo lo que hace scaffolds. Ahorra tiempo, solo habr铆a que darle dise帽o y todo listo,

Ejemplo utilizado:

rails g scaffold Book title:string author:string description:string isbn:string pages_count:integer
Ojala actualizaran cursos de Ruby... y si no se puede, pues tendr茅 que hacerlo yo!

Scaffold es un generador de Rails, que permite crear una estructura inicial de modelo, vistas y controladores para comenzar a trabajar.

Para crear un scaffold se utiliza el comando rails g scaffold seguido de los campos que tendr谩 el modelo. Por ejemplo:

rails g scaffold Book title:string author:string description:text
isbn:string pages:integer

Luego de usar el comando se generar谩 una serie de archivos. Todo lo que diga invoke har谩 referencia a un invocador. Algunos son:

  • active_record: Crea dos archivos para las migraciones
  • resource_route: Crea las rutas de nuestro elemento. Esto incluye controladores y acciones (ndex, edit, show, new, destroy)
  • scaffold_controller: Crea un controlador de nuestro recurso
  • helper: Crea abstracciones dentro de las vistas
  • jbuilder: Permite crear archivos de tipo JSON
  • assets / scss : Crea un archivo tipo SASS en la carpeta asstes para modificar estilos.

Cuando se utiliza al m茅todo resources, este crea una serie de rutas y sus m茅todos para acceder a un recurso determinado.


Para acceder a los recursos creados por scaffold basta con entrar a la primera ruta en el navegador. Ah铆 se mostrar谩 una tabla con todos los registros creados con la posibilidad de editarlos o eliminarlos, y un bot贸n para entrar a un formulario y crear un nuevo registro.


Al revisar el archivo config>routes.rb vemos que se agreg贸 la l铆nea resource :books. Con esto se a帽aden las rutas creadas, que corresponden a una acci贸n del controlado, que tambi茅n creo scaffold.

Muy buena la explicaci贸n!!!

Buenisimi video, pude aprender cosas que en clases anteriores no me sal铆an al momento de conectar con el servidor.