¿Cómo crear un blog con Ruby On Rails?

Primero tengamos una breve descripción general de Ruby on Rails: - Ruby on Rails es un marco para el lenguaje Ruby, que se utiliza para el desarrollo rápido de aplicaciones web. Lo hace permitiéndole concentrarse en resolver los problemas de sus clientes y no quedar atrapado en la construcción de una infraestructura para respaldar los problemas de sus clientes.

Seamos realistas, no desea crear una capa de acceso a la base de datos cada vez que inicia un nuevo proyecto. Tampoco querrás implementar un patrón MVC completamente funcional de forma regular. Este es el objetivo de los marcos; le brindan un punto de partida sobre el cual puede construir. Un poco más sobre MVC: Vale la pena mencionar MVC (Modelo-Vista-Controlador) porque puede ser uno de los factores que disuade a las personas de probar marcos como Rails. Es una forma bastante avanzada de programar el estilo arquitectónico más famoso.

Veámoslos brevemente: - MODELO: - La capa de modelo es donde usted define las clases para los datos que su aplicación usará/almacenará. Por ejemplo, si desea almacenar publicaciones para un blog, tendrá un modelo "Publicación". El modelo tiene la capacidad de interactuar con la base de datos, recuperar y almacenar datos. Esta funcionalidad se obtiene heredándola de la superclase ActiveRecord. Cualquier método que actúe sobre estos datos también debe incluirse en el modelo. VER: - La capa de vista tiene un propósito principal: devolver lo relevante.

HTML que se representará en el navegador de los usuarios. En Rail, una vista se mantiene en un archivo erb (Embedded Ruby), que contiene HTML y declaraciones Ruby incrustadas. CONTROLADOR:- Sin el controlador, no pasaría nada. El controlador interactúa con el modelo para recuperar y almacenar datos. Luego pasará todos los datos adquiridos del modelo a la vista. La vista devuelve el HTML resultante al controlador y el controlador lo envía de vuelta al navegador del usuario. CREAR UN BLOG DESDE CERO USANDO RUBY ON RAILS: - Para crear un nuevo proyecto en Ruby On Rails (ROR), debe escribir el siguiente comando desde la terminal o el símbolo del sistema.

Ruby on Rails new myblog -d mysql //-d mysql specifies rails to use mysql.Default it uses sqllite. Requirements:- –>It should create a blog and allow the user to write the posts. –>Other users can comment on posts. //many lines can be added here based on requirements APPROACH:- –>We need to have model for both Posts and Comments. –>We also need to define relationship between these models i.e- :one to one :one to many :many to many etc SCAFFOLDING:- –>Scaffold in rails is a script which will generate suitable controllers,models,view based on used parameters and rails command.

We can use this command to create our post and comment rails generate scaffold post title:string body:text rails generate scaffold comment name:string body:text post:reference Relating the Post and Comment Models:- –>Now as the two models are created,we need to define relationships between models Post.rb class Post < ActiveRecord::Base has_many :comments end Comment.rb class Comment < ActiveRecord::Base belongs_to :post end TO CREATE A DATABASE AND TABLES:- Now that we have created the models, we need to create the database then create tables to hold information about posts and comments.

To create the database we need to add the username and password into database.yml file i.e:- development: adapter: mysql encoding: utf8 reconnect: false database: myblog_development pool: 5 username: root password: yourrootpassword host: localhost – – > After we have configured the database we need to create the database:- cd myblog //from command prompt rake db:create Database Migration In Ruby on Rails, a Migration is the name given to the process of moving your database from one state to another.

Algunos ejemplos de migración de su base de datos de un estado a otro son:

  •   Creando tablas
  •   Quitar tablas
  •   Agregar nuevos campos
  •   Eliminando campos

When you created the two models for posts and comments using scaffold, several files were created automatically. In particular, migration files were created in the dbmigrate folder. These files are used to create the tables for the post and comment models. To build the tables using the migration files you should run the following command: rake db:migrate The “posts” and “comments” tables should now be created. SEE RESULTS:- –>Yes thats it!!!

we have created our project and we can see the results.Just start the server from terminal and give:- rails s or rails s -p 3001 // -p option is used to use a different port,default it will use port 3000. –>Now open the browser and see the result at http://localhost:3000.Before that we need to modify the default routes in configuration/routes.rb file and change the routes path accordingly.

Póngase en contacto con nosotros.



Suscríbete para recibir las últimas actualizaciones

Artículos Relacionados

Deja un comentario

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *

Spanish
English
English
Japanese
German
French
Spanish

envíanos whatsapp

Salir de la versión móvil