In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly talks about "what are the Rails, MVC and the most commonly used Rails commands". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn what are the Rails, MVC and the most commonly used Rails commands.
What is Rails?
Rails is a web application framework. According to the Model-View-Controller (MVC) pattern, it includes everything you need to create a database-supported web application. MVC divides the application into three layers: model, view, and controller, each with specific tasks.
Model-View-Controller (MVC) structure diagram
Model layer
The model layer represents domain models (such as Account, Product, Person, Post, etc.) and outlines the business logic unique to the application.
In Rails, the model classes supported by the database are derived from ActiveRecord::Base. Active Record enables users to represent the data of database rows as objects and decorate these data objects with business logic methods. Most Rails models are supported by databases, and they can also be Ruby normal classes or Ruby classes that implement a set of interfaces provided by Active Model modules.
Control layer
The function of the control layer is to process incoming HTTP requests and give appropriate responses. Usually this layer means returning HTML, but the Rails controller can also generate XML, JSON, PDF, mobile-specific views, and other formats.
The controller loads and manipulates the model and renders the view template to generate the appropriate HTTP response. In Rails, the incoming request is sent by the Action Dispatch to the appropriate controller, and the control class comes from the ActionController::Base. Action Dispatch and Action Controller are tied together in Action Pack.
Image source: unsplash
View layer
The view layer consists of "templates" and is mainly responsible for providing an appropriate description of the application resources. Templates can be in many formats, but most view templates are HTML (ERB files) with embedded Ruby code. The view usually generates a controller response or an e-mail body. In Rails, view generation is handled by Action View.
Develop a new Rails application
First build an application from scratch, and before that, make sure that Ruby, RubyGems, and Bundler are installed in the system. Open the terminal and navigate to a directory that has permission to create files. The first thing to do is to install Rails and build a new Rails application by running the railsnew command.
To create a Rails that only supports API from scratch, the api should be created after the name of the Rails application: railsnew-- database=postgresql-- api (it's easier to configure the application with the Postgresql database, but don't forget to install the database before running the command). For example: rails new Gallery-- database=postgresql-api.
By using the-- api flag, Rails can remove many of the default features and middleware (mostly involving useless browsers). The controller inherits ActionController::API rather than ActionController::Base, and the generator skips generating views. No change is required to set up resources for Rails builds that only support API.
Start running bundle install after adding all the required gem to the Gemfile.
Initialize the database: rails db:create
Run Rails server: rails s
Rails generation
The primary goal of the Rails team is to build core application functions efficiently. The Rails system has a large number of generators that can help users complete some manual jobs. In addition to saving time, the generator has some other advantages:
The generator can set the basic specifications for the application test suite. They provide users with basic examples rather than writing complex logical tests.
The generator is set to operate in the same way, which standardizes the code and helps users develop more efficiently because they don't have to worry too much about spelling, syntax errors, or other related vulnerabilities that may occur in handwritten code.
The generator follows Rails best practices, including the use of RESTful naming patterns, removal of duplicate code, usage sections, and many other best type design patterns.
However, some generators create a considerable amount of code. If you do not use a certain code, it will cause unnecessary confusion in the application code, which will be troublesome to future programmers. So when is the best time to use a generator? All Rails generators enter terminals as commands and follow the following syntax:
Rails generate-no-test-framework
-- no-test-framework is a flag intended to remind the generator not to create any tests for newly generated models, controllers, and so on. Users do not need flags when running their own Rails applications, which is very helpful in building test suites quickly.
To improve efficiency, Rails simplifies the generate method to g, so the above CLI command can be simplified to:
Rails g-- no-test-framework
Image source: unsplash
The following are the main generators provided by Rails. The author will give examples to illustrate:
Migration generator
Rails has a set of specification-compliant high-quality migration generators that manage database schemas effectively. After drawing the domain model, you can proceed to the next step. First use the database in the case base application to migrate and update the painters table. Use the following command to add a column to the table and name it portrait:
Railsg migration add_portrait_to_painters portrait:string-no-test-framework
The terminal shows that the migration file 20200928055457_add_portrait_to_painters.rb. Because the migration file name cannot be duplicated, the generator adds a timestamp to the file name. Something amazing happened-- open the file created in the db/migrat directory, and it should now look like this:
Class AddPortraitToPainters < ActiveRecord::Migration [6.0] def change add_column: painters,: portrait,:string end end
Did you notice the role of the generator? It automatically senses that the user wants to add a new column and builds the add_column method call. How do you do this?
Practice has proved that the method of naming migration files is very important. By adding add_ text to the name, it sends a signal to the migration generator that the purpose of this schema change is to add one or more columns to the table.
So how does it know which table the user wants to add? It appends _ painters text to the end of the migration name to tell Rails users that the table they want to change is the painters table. Finally, the generator is told that the name of the new column is portrait and the data type is string by adding portrait:string text to the end of the command.
Users can update the database schema by running rails db:migrate, which also reflects this change.
To delete a column, you can run another migration:
Railsg migration remove_portrait_from_painters portrait:string
If you open this migration file, you will see the following code:
Class RemovePortraitToPainters < ActiveRecord::Migration [6.0] def change remove_column: painters,: portrait,:string end end
After running rails db:migrate, the schema is also updated. You can use this command when you need to run any pending migrations.
Railsdb:migrate:reset: it deletes the database information, runs the migration in the new database, and reloads the seed data.
Railsdb:seed: load data from the file: db/seeds.rb into the database. This approach is useful for populating the database with the initial data required by the Rails project.
Railsdb:rollback: rolls back the last migration performed. It undoes the last migration, and the user can then edit the file and rerun rails db:migrate. Note that this command is used with caution as it is extremely destructive and is likely to result in data loss. The runtime must make sure that it is fully aware of the results of the run.
Model generator
This is a type of generator that is often used. It is suitable for writing the core code needed to create models and associated database tables without overcomplicating the application. Generally speaking, the model name (singular and uppercase) and model parameters are required.
Next, add a new model for the Painter application with name, bio, and genre columns, and you can use the model builder with the following CLI command:
Railsg model Painter name:string genre:string bio:text
If the data type is a string, you do not need to specify the type after the column name because it is the default data type. So it is as follows:
Railsg model Painter name genre bio:text
Because of its high level, this step has been created:
Add a database migration of a table and name, genre, and bio columns
Inherit the model file from ApplicationRecord (from Rails 5)
Let's next create another model that belongs to Painter, Painting:
Railsg model Painting name image painter:belongs_to
Remember to generate code with the has_many macro command first; only code with belongs_to is useful when running the migration, otherwise you will get an error code:
ActiveRecord::StatementInvalid:PG::UndefinedTable: ERROR: relation "" doesnot exist
Running this generator creates a migration file and a Painter and Painting model. This particular generator creates a number of different functions with a single command and is generated with only the simplest code. Then turn to your own model and make sure that the appropriate relationships are established (has_many, belongs_to).
The next step is to create a migration: rails db:create and rails db:migrate to migrate the table. Users can test the connection in the console, just run rails c and create some new examples, whether it is correct or not, and then test the correlation (for example, Painter.all.first.painting can check the painting of the first painter)
Image source: unsplash
Control generator
Running the rails g controller command provides a control file (for adding appropriate actions) and the corresponding view folder:
Railsg controller paintings
Resource Generator
If users use the front-end MVC architecture during API creation, or if they just want to create views manually, the resource generator is a preferred choice for writing code. Create a Painting resource:
Railsg resource Painting name image painter:belongs_to
Because no data types are written for name and image, it is a string by default. Add painter:belongs_to to specify the relationship between the two tables, and set a column of painter_id in the paintings table. You can also write the above command using references (the result is the same):
Railsg resource Painting name image painter:references
This is another example of writing the same command for different models:
Railsg resource Answer content correct_answer:boolean question:belongs_to
What does the current application have with the generator?
A migration file that can create a new database table in the generator for the properties passed to it
Inherit the model file from ApplicationRecord (starting with Rails 5, see above considerations)
Inherits the controller file of ApplicationController
A view directory without a view template file
View helper file
The Coffeescript file for the specific JavaScripts for the controller
Scss file for controller styl
The complete resource call within the routes.rb file
The resource generator is an intelligent generator that creates some of the core functions required for full-featured resources without causing too much code bloat.
Routin
Image source: unsplash
The last one may not be very common. Resources:paintings is often seen as a "magic" route that contains all the RESTful routes needed to perform CRUD in the application. So what does resources:paintings turn into? It is easier to run rake routes with a filter, so that only the route of the paintings will be rendered:
Rake routes | grep painting
Resources automatically creates each route and makes it available to the controller. Opening the paintings_controller.rb file can be interesting: none of the actions that appear in the route list exist. It creates very little code and only needs to add the functionality needed by the application.
Scaffold generator
Rails g scaffold User username:string so far, I believe you have a deeper understanding of "Rails, MVC and the most commonly used Rails commands". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.