如何构建Ruby on Rails应用程序

介绍 (Introduction)

Rails is a web application framework written in Ruby. It takes an opinionated approach to application development, assuming that set conventions best serve developers where there is a common goal. Rails therefore offers conventions for handling routing, stateful data, asset management, and more to provide the baseline functionality that most web applications need.

Rails是一个用Ruby编写的Web应用程序框架。 假设设置约定最适合有共同目标的开发人员,则它采用自觉的方法进行应用程序开发。 因此,Rails提供了用于处理路由,状态数据,资产管理等的约定,以提供大多数Web应用程序所需的基线功能。

Rails follows the model-view-controller (MCV) architectural pattern, which separates an application’s logic, located in models, from the routing and presentation of application information. This organizational structure — along with other conventions that allow developers to extract code into helpers and partials — ensures that application code isn’t repeated unnecessarily.

Rails遵循模型视图控制器 (MCV)架构模式,该模式将位于模型中的应用程序逻辑与应用程序信息的路由和表示分开。 这种组织结构以及允许开发人员将代码提取到帮助程序局部代码中的其他约定,确保了不会不必要地重复应用程序代码。

In this tutorial, you will build a Rails application that will enable users to post information about sharks and their behavior. It will be a good starting point for future application development.

在本教程中,您将构建一个Rails应用程序,使用户能够发布有关鲨鱼及其行为的信息。 这将是未来应用程序开发的良好起点。

先决条件 (Prerequisites)

To follow this tutorial, you will need:

要遵循本教程,您将需要:

  • A local machine or development server running Ubuntu 18.04. Your development machine should have a non-root user with administrative privileges and a firewall configured with ufw. For instructions on how to set this up, see our Initial Server Setup with Ubuntu 18.04 tutorial.

    运行Ubuntu 18.04的本地计算机或开发服务器。 您的开发机器应具有具有管理特权的非root用户,以及使用ufw配置的防火墙。 有关如何进行此设置的说明,请参阅我们的《 Ubuntu 18.04初始服务器设置》教程。

  • Node.js and npm installed on your local machine or development server. This tutorial uses Node.js version 10.16.3 and npm version 6.9.0. For guidance on installing Node.js and npm on Ubuntu 18.04, follow the instructions in the “Installing Using a PPA” section of How To Install Node.js on Ubuntu 18.04.

    安装在本地计算机或开发服务器上的Node.jsnpm 。 本教程使用Node.js 10.16.3版和npm 6.9.0版。 有关在Ubuntu 18.04上安装Node.js和npm的指导,请遵循如何在Ubuntu 18.04上安装Node.js的“使用PPA安装”部分中的说明。

  • Ruby, rbenv, and Rails installed on your local machine or development server, following Steps 1-4 in How To Install Ruby on Rails with rbenv on Ubuntu 18.04. This tutorial uses Ruby 2.5.1, rbenv 1.1.2, and Rails 5.2.0.

    遵循在Ubuntu 18.04上如何使用rbenv安装Ruby on Rails中的步骤1-4中的步骤,将Ruby, rbenv和Rails安装在本地计算机或开发服务器 。 本教程使用Ruby 2.5.1 ,rbenv 1.1.2和Rails 5.2.0 。

第1步-安装SQLite3 (Step 1 — Installing SQLite3)

Before creating our Rails shark application, we will need to ensure that we have a database to store user data. Rails is configured to use SQLite by default, and this is often a good choice in development. Since our application data doesn’t require a high level programmatic extensibility, SQLite will meet our needs.

在创建Rails shark应用程序之前,我们需要确保我们有一个数据库来存储用户数据。 默认情况下,Rails配置为使用SQLite ,这在开发中通常是一个不错的选择。 由于我们的应用程序数据不需要高级的程序可扩展性,因此SQLite将满足我们的需求。

First, update your package index:

首先,更新您的包裹索引:

  • sudo apt update

    sudo apt更新

Next, install the sqlite3 and libsqlite3-dev packages:

接下来,安装sqlite3libsqlite3-dev软件包:

  • sudo apt install sqlite3 libsqlite3-dev

    须藤apt install sqlite3 libsqlite3-dev

This will install both SQLite and its required development files.

这将安装SQLite及其必需的开发文件。

Check your version to confirm that the installation was successful:

检查您的版本以确认安装成功:

  • sqlite3 --version

    sqlite3-版本

   
   
Output
3.22.0 2018-01-22 18:45:57 0c55d179733b46d8d0ba4d88e01a25e10677046ee3da1d5b1581e86726f2alt1

With SQLite installed, you are ready to begin developing your application.

安装了SQLite之后,就可以开始开发应用程序了。

第2步-创建一个新的Rails项目 (Step 2 — Creating a New Rails Project)

With our database installed, we can create a new Rails project and look at some of the default boilerplate code that Rails gives us with the rails new command.

安装好数据库后,我们可以创建一个新的Rails项目,并查看Rails使用rails new命令为我们提供的一些默认样板代码。

Create a project called sharkapp with the following command:

使用以下命令创建一个名为sharkapp的项目:

  • rails new sharkapp

    Rails New Sharkapp

You will see a good deal of output telling you what Rails is creating for your new project. The output below highlights some significant files, directories, and commands:

您将看到大量输出,告诉您Rails正在为新项目创建什么。 下面的输出突出显示了一些重要的文件,目录和命令:


   
   
Output
create . . . create Gemfile . . . create app . . . create app/controllers/application_controller.rb . . . create app/models/application_record.rb . . . create app/views/layouts/application.html.erb . . . create config create config/routes.rb create config/application.rb . . . create config/environments create config/environments/development.rb create config/environments/production.rb create config/environments/test.rb . . . create config/database.yml create db create db/seeds.rb . . . run bundle install . . . Bundle complete! 18 Gemfile dependencies, 78 gems now installed. Use `bundle info [gemname]` to see where a bundled gem is installed. . . . * bin/rake: Spring inserted * bin/rails: Spring inserted

The output highlighted here tells you that Rails has created the following:

此处突出显示的输出告诉您Rails已创建以下内容:

  • Gemfile: This file lists the gem dependencies for your application. A gem is a Ruby software package, and a Gemfile allows you to manage your project’s software needs.

    Gemfile :此文件列出了您的应用程序的gem依赖项。 gem是Ruby软件包,而Gemfile则允许您管理项目的软件需求。

  • app: The app directory is where your main application code lives. This includes the models, controllers, views, assets, helpers, and mailers that make up the application itself. Rails gives you some application-level boilerplate for the MCV model to start out in files like app/models/application_record.rb, app/controllers/application_controller.rb, and app/views/layouts/application.html.erb.

    appapp目录是您的主要应用程序代码所在的目录。 这包括组成应用程序本身的模型,控制器,视图,资产,帮助程序和邮件程序。 Rails为您提供了MCV模型的一些应用程序级样板,可以从诸如app/models/application_record.rbapp/controllers/application_controller.rbapp/views/layouts/application.html.erb

    • config/routes.rb: Your application’s route declarations live in this file.

      config/routes.rb :您的应用程序的路由声明位于此文件中。

    • config/application.rb: General settings for your application components are located in this file.

      config/application.rb :应用程序组件的常规设置位于此文件中。

    config: This directory contains your application’s configuration settings:

    config :此目录包含您的应用程序的配置设置:

  • config/environments: This directory is where configuration settings for your environments live. Rails includes three environments by default: development, production, and test.

    config/environments :此目录是您的环境的配置设置所在的位置。 Rails默认包括三种环境: developmentproductiontest

  • config/database.yml: Database configuration settings live in this file, which is broken into four sections: default, development, production, and test. Thanks to the Gemfile that came with the rails new command, which included the sqlite3 gem, our config/database.yml file has its adapter parameter set to sqlite3 already, specifying that we will use an SQLite database with this application.

    config/database.yml :数据库配置设置位于该文件中,该文件分为四个部分: defaultdevelopmentproductiontest 。 感谢rails new命令随附的Gemfile(包括sqlite3 gem),我们的config/database.yml文件的adapter参数已设置为sqlite3 ,从而指定我们将在此应用程序中使用SQLite数据库。

  • db: This folder includes a directory for database migrations called migrate, along with the schema.rb and seeds.rb files. schema.db contains information about your database, while seeds.rb is where you can place seed data for the database.

    db :这个文件夹包括了数据库目录迁移migrate ,与沿schema.rbseeds.rb文件。 schema.db包含有关您的数据库的信息,而seeds.rb是您可以在其中放置数据库的种子数据的位置。

Finally, Rails runs the bundle install command to install the dependencies listed in your Gemfile.

最后,Rails运行bundle install命令安装Gemfile列出的依赖Gemfile

Once everything is set up, navigate to the sharkapp directory:

一切设置完成后,导航至sharkapp目录:

  • cd sharkapp

    cd sharkapp

You can now start the Rails server to ensure that your application is working, using the rails server command. If you are working on your local machine, type:

现在,您可以使用rails server命令启动Rails服务器以确保您的应用程序正常运行。 如果您在本地计算机上工作,请键入:

  • rails server

    Rails服务器

Rails binds to localhost by default, so you can now access your application by navigating your browser to locahost:3000, where you will see the following image:

Rails默认绑定到localhost ,因此您现在可以通过将浏览器导航到locahost:3000来访问您的应用程序,您将在其中看到以下图像:

If you are working on a development server, first ensure that connections are allowed on port 3000:

如果在开发服务器上工作,请首先确保在端口3000上允许连接:

  • sudo ufw allow 3000

    须藤ufw允许3000

Then start the server with the --binding flag, to bind to your server IP:

然后使用--binding标志启动服务器,以绑定到服务器IP:

  • rails server --binding=your_server_ip

    Rails服务器--binding = your_server_ip

Navigate to http://your_server_ip:3000 in your browser, where you will see the Rails welcome message.

在浏览器中导航到http:// your_server_ip :3000 ,您将在其中看到Rails的欢迎消息。

Once you have looked around, you can stop the server with CTRL+C.

环顾四周后,可以使用CTRL+C停止服务器。

With your application created and in place, you are ready to start building from the Rails boilerplate to create a unique application.

创建并放置好应用程序之后,您就可以开始从Rails样板开始构建以创建唯一的应用程序。

步骤3 —搭建应用程序 (Step 3 — Scaffolding the Application)

To create our shark information application, we will need to create a model to manage our application data, views to enable user interaction with that data, and a controller to manage communication between the model and the views. To build these things we will use the rails generate scaffold command, which will give us a model, a database migration to alter the database schema, a controller, a full set of views to manage Create, Read, Update, and Delete (CRUD) operations for the application, and templates for partials, helpers, and tests.

要创建我们的鲨鱼信息应用程序,我们将需要创建一个模型来管理我们的应用程序数据,创建视图以允许用户与该数据进行交互,并创建一个控制器来管理模型与视图之间的通信。 为了构建这些东西,我们将使用rails generate scaffold命令,该命令将为我们提供模型, 数据库迁移以更改数据库模式,控制器,用于管理创建,读取,更新和删除 (CRUD)的全套视图。应用程序的操作,以及局部,帮助程序和测试的模板。

Because the generate scaffold command does so much work for us, we’ll take a closer look at the resources it creates to understand the work that Rails is doing under the hood.

由于generate scaffold命令对我们有很多工作,因此,我们将仔细研究它所创建的资源,以了解Rails在幕后所做的工作。

Our generate scaffold command will include the name of our model and the fields we want in our database table. Rails uses Active Record to manage relationships between application data, constructed as objects with models, and the application database. Each of our models is a Ruby class, while also inheriting from the ActiveRecord::Base class. This means that we can work with our model class in the same way that we would work with a Ruby class, while also pulling in methods from Active Record. Active Record will then ensure that each class is mapped to a table in our database, and each instance of that class to a row in that table.

我们的generate scaffold命令将包含我们的模型的名称以及我们数据库表中想要的字段。 Rails使用Active Record来管理应用程序数据和应用程序数据库之间的关系,该应用程序数据被构造为带有模型的对象。 我们的每个模型都是Ruby类 ,同时还继承自ActiveRecord::Base类。 这意味着我们可以像使用Ruby类一样使用模型类,同时还可以从Active Record中提取方法。 然后,Active Record将确保将每个类映射到我们数据库中的表,并将该类的每个实例映射到该表中的一行。

Type the following command to generate a Shark model, controller, and associated views:

键入以下命令以生成Shark模型,控制器和关联的视图:

  • rails generate scaffold Shark name:string facts:text

    Rails生成脚手架Shark名称:string facts:文本

With name:string and facts:text we are giving Rails information about the fields we would like in our database table and the type of data they should accept. Both will give us room to input what we would like, though text will allow more characters for shark facts.

通过name:stringfacts:text我们为Rails提供了有关我们希望数据库表中的字段及其应接受的数据类型的信息。 两者都将为我们提供输入所需内容的空间,尽管text将为鲨鱼事实提供更多字符。

When you type this command, you will again see a long list of output that explains everything Rails is generating for you. The output below highlights some of the more significant things for our setup:

当您键入此命令时,您将再次看到一长串输出,解释了Rails为您生成的一切。 下面的输出突出显示了我们设置中一些更重要的事情:


   
   
Output
invoke active_record create db/migrate/20190804181822_create_sharks.rb create app/models/shark.rb . . . invoke resource_route route resources :sharks invoke scaffold_controller create app/controllers/sharks_controller.rb invoke erb create app/views/sharks create app/views/sharks/index.html.erb create app/views/sharks/edit.html.erb create app/views/sharks/show.html.erb create app/views/sharks/new.html.erb create app/views/sharks/_form.html.erb . . .

Rails has created the model at app/models/shark.rb and a database migration to go with it: db/migrate/20190804181822_create_sharks.rb. The timestamp on your migration file will differ from what you see here.

Rails在app/models/shark.rb上创建了模型,并进行了数据库迁移: db/migrate/ 20190804181822 _create_sharks.rb 。 迁移文件上的时间戳将与此处看到的不同。

It has also created a controller, app/controllers/sharks_controller.rb, as well as the views associated with our application’s CRUD operations, collected under app/views/sharks. Among these views is a partial, _form.html.erb, that contains code used across views.

它还创建了一个控制器app/controllers/sharks_controller.rb ,以及与我们的应用程序的CRUD操作关联的视图,这些视图收集在app/views/sharks 。 这些视图中有一个_form.html.erb部分,其中包含跨视图使用的代码。

Finally, Rails added a new resourceful route, resources :sharks, to config/routes.rb. This enables the Rails router to match incoming HTTP requests with the sharks controller and its associated views.

最后,Rails在config/routes.rb添加了一个新的资源丰富的路由resources :sharks 。 这使Rails路由器能够将传入的HTTP请求与sharks控制器及其关联的视图进行匹配。

Though Rails has done much of the work of building out our application code for us, it is worth taking a look at some files to understand what is happening.

尽管Rails为我们完成了构建应用程序代码的大量工作,但是值得看一下一些文件以了解正在发生的事情。

First, let’s look at the controller file with the following command:

首先,让我们使用以下命令查看控制器文件:

  • cat app/controllers/sharks_controller.rb

    猫app / controllers / sharks_controller.rb

   
   
Output
class SharksController < ApplicationController before_action :set_shark, only: [:show, :edit, :update, :destroy] # GET /sharks # GET /sharks.json def index @sharks = Shark.all end # GET /sharks/1 # GET /sharks/1.json def show end # GET /sharks/new def new @shark = Shark.new end # GET /sharks/1/edit def edit end # POST /sharks # POST /sharks.json def create @shark = Shark.new(shark_params) respond_to do |format| if @shark.save format.html { redirect_to @shark, notice: 'Shark was successfully created.' } format.json { render :show, status: :created, location: @shark } else format.html { render :new } format.json { render json: @shark.errors, status: :unprocessable_entity } end end end # PATCH/PUT /sharks/1 # PATCH/PUT /sharks/1.json def update respond_to do |format| if @shark.update(shark_params) format.html { redirect_to @shark, notice: 'Shark was successfully updated.' } format.json { render :show, status: :ok, location: @shark } else format.html { render :edit } format.json { render json: @shark.errors, status: :unprocessable_entity } end end end # DELETE /sharks/1 # DELETE /sharks/1.json def destroy @shark.destroy respond_to do |format| format.html { redirect_to sharks_url, notice: 'Shark was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_shark @shark = Shark.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def shark_params params.require(:shark).permit(:name, :facts) end end

The controller is responsible for managing how information gets fetched and passed to its associated model, and how it gets associated with particular views. As you can see, our sharks controller includes a series of methods that map roughly to standard CRUD operations. However, there are more methods than CRUD functions, to enable efficiency in the case of errors.

控制器负责管理如何获取信息并将其传递到其关联模型,以及如何将其与特定视图关联。 如您所见,我们的sharks控制器包括一系列大致映射到标准CRUD操作的方法。 但是,除CRUD功能外,还有更多方法可以在发生错误的情况下提高效率。

For example, consider the create method:

例如,考虑create方法:

~/sharkapp/app/controllers/sharks_controller.rb
〜/ sharkapp / app / controllers / sharks_controller.rb
. . .
  def create
    @shark = Shark.new(shark_params)

    respond_to do |format|
      if @shark.save
        format.html { redirect_to @shark, notice: 'Shark was successfully created.' }
        format.json { render :show, status: :created, location: @shark }
      else
        format.html { render :new }
        format.json { render json: @shark.errors, status: :unprocessable_entity }
      end
    end
  end
. . .

If a new instance of the Shark class is successfully saved, redirect_to will spawn a new request that is then directed to the controller. This will be a GET request, and it will be handled by the show method, which will show the user the shark they’ve just added.

如果成功保存了Shark类的新实例,则redirect_to将产生一个新请求,然后将其定向到控制器。 这将是一个GET请求,并将由show方法处理,该方法将向用户显示他们刚刚添加的鲨鱼。

If there is a failure, then Rails will render the app/views/sharks/new.html.erb template again rather than making another request to the router, giving users another chance to submit their data.

如果出现故障,Rails将再次渲染app/views/sharks/new.html.erb模板,而不是向路由器发出另一个请求,从而为用户提供了另一个提交数据的机会。

In addition to the sharks controller, Rails has given us a template for an index view, which maps to the index method in our controller. We will use this as the root view for our application, so it’s worth taking a look at it.

除了sharks控制器外,Rails还为我们提供了index视图的模板,该模板映射到控制器中的index方法。 我们将其用作应用程序的根视图,因此值得一看。

Type the following to output the file:

输入以下内容以输出文件:

  • cat app/views/sharks/index.html.erb

    猫app / views / sharks / index.html.erb

   
   
Output
<p id="notice"><%= notice %></p> <h1>Sharks</h1> <table> <thead> <tr> <th>Name</th> <th>Facts</th> <th colspan="3"></th> </tr> </thead> <tbody> <% @sharks.each do |shark| %> <tr> <td><%= shark.name %></td> <td><%= shark.facts %></td> <td><%= link_to 'Show', shark %></td> <td><%= link_to 'Edit', edit_shark_path(shark) %></td> <td><%= link_to 'Destroy', shark, method: :delete, data: { confirm: 'Are you sure?' } %></td> </tr> <% end %> </tbody> </table> <br> <%= link_to 'New Shark', new_shark_path %>

The index view iterates through the instances of our Shark class, which have been mapped to the sharks table in our database. Using ERB templating, the view outputs each field from the table that is associated with an individual shark instance: name and facts.

index视图遍历Shark类的实例,这些实例已映射到数据库中的sharks表。 使用ERB模板 ,视图输出表中与单个鲨鱼实例相关联的每个字段: namefacts

The view then uses the link_to helper to create a hyperlink, with the provided string as the text for the link and the provided path as the destination. The paths themselves are made possible through the helpers that became available to us when we defined the sharks resourceful route with the rails generate scaffold command.

然后,视图使用link_to帮助程序创建超链接,其中提供的字符串作为链接的文本,提供的路径作为目的地。 当我们使用rails generate scaffold命令定义sharks足智多谋的路线时,这些路径本身就可以通过帮助者来实现。

In addition to looking at our index view, we can also take a look at the new view to see how Rails uses partials in views. Type the following to output the app/views/sharks/new.html.erb template:

除了查看index视图之外,我们还可以查看new视图,以了解Rails如何在视图中使用局部视图。 输入以下内容以输出app/views/sharks/new.html.erb模板:

  • cat app/views/sharks/new.html.erb

    猫app / views / sharks / new.html.erb

   
   
Output
<h1>New Shark</h1> <%= render 'form', shark: @shark %> <%= link_to 'Back', sharks_path %>

Though this template may look like it lacks input fields for a new shark entry, the reference to render 'form' tells us that the template is pulling in the _form.html.erb partial, which extracts code that is repeated across views.

尽管此模板看起来好像缺少新的鲨鱼条目的输入字段,但对render 'form'的引用告诉我们该模板正在拉入_form.html.erb部分,该部分提取了在视图之间重复的代码。

Looking at that file will give us a full sense of how a new shark instance gets created:

查看该文件将使我们全面了解如何创建新的Shark实例:

  • cat app/views/sharks/_form.html.erb

    猫app / views / sharks / _form.html.erb

   
   
Output
<%= form_with(model: shark, local: true) do |form| %> <% if shark.errors.any? %> <div id="error_explanation"> <h2><%= pluralize(shark.errors.count, "error") %> prohibited this shark from being saved:</h2> <ul> <% shark.errors.full_messages.each do |message| %> <li><%= message %></li> <% end %> </ul> </div> <% end %> <div class="field"> <%= form.label :name %> <%= form.text_field :name %> </div> <div class="field"> <%= form.label :facts %> <%= form.text_area :facts %> </div> <div class="actions"> <%= form.submit %> </div> <% end %>

This template makes use of the form_with form helper. Form helpers are designed to facilitate the creation of new objects from user input using the fields and scope of particular models. Here, form_with takes model: shark as an argument, and the new form builder object that it creates has field inputs that correspond to the fields in the sharks table. Thus users have form fields to enter both a shark name and shark facts.

该模板使用form_with 表单帮助器 。 表单帮助程序旨在使用特定模型的字段和范围,通过用户输入促进创建新对象。 在这里, form_withmodel: shark作为参数,并且它创建的新的表单构建器对象具有与sharks表中的字段相对应的字段输入。 因此,用户可以在表单字段中输入鲨鱼name和鲨鱼facts

Submitting this form will create a JSON response with user data that the rest of your application can access by way of the params method, which creates a ActionController::Parameters object with that data.

提交此表单将创建一个带有用户数据的JSON响应,您的应用程序的其余部分可以通过params方法访问该用户数据,该方法使用该数据创建一个ActionController::Parameters对象。

Now that you know what rails generate scaffold has produced for you, you can move on to setting the root view for your application.

现在您已经知道为您rails generate scaffold哪些rails generate scaffold ,您可以继续设置应用程序的根视图。

第4步-创建应用程序根视图并测试功能 (Step 4 — Creating the Application Root View and Testing Functionality)

Ideally, you want the landing page of your application to map to the application’s root, so users can immediately get a sense of the application’s purpose.

理想情况下,您希望应用程序的登录页面映射到应用程序的根目录,以便用户可以立即了解应用程序的用途。

There are a number of ways you could handle this: for example, you could create a Welcome controller and an associated index view, which would give users a generic landing page that could also link out to different parts of the application. In our case, however, having users land on our index sharks view will be enough of an introduction to the application’s purpose for now.

您可以通过多种方法来处理此问题:例如,您可以创建一个Welcome控制器和一个关联的index视图,这将为用户提供通用的登录页面,该页面也可以链接到应用程序的不同部分。 但是,在我们的情况下,让用户登陆我们的index鲨鱼视图就足够了。

To set this up, you will need to modify the routing settings in config/routes.rb to specify the root of the application.

要进行设置,您将需要修改config/routes.rb的路由设置以指定应用程序的根目录。

Open config/routes.rb for editing, using nano or your favorite editor:

使用nano或您喜欢的编辑器打开config/routes.rb进行编辑:

  • nano config/routes.rb

    纳米配置/ routes.rb

The file will look like this:

该文件将如下所示:

~/sharkapp/config/routes.rb
〜/ sharkapp / config / routes.rb
Rails.application.routes.draw do
  resources :sharks
  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end

Without setting something more specific, the default view at http://localhost:3000 or http://your_server_ip:3000 will be the default Rails welcome page.

如果没有设置更具体的内容,位于http://localhost:3000http:// your_server_ip :3000的默认视图将是默认的Rails欢迎页面。

In order to map the root view of the application to the index view of the sharks controller, you will need to add the following line to the file:

为了将应用程序的根视图映射到sharks控制器的index视图,您将需要在文件中添加以下行:

~/sharkapp/config/routes.rb
〜/ sharkapp / config / routes.rb
Rails.application.routes.draw do
  resources :sharks

  root 'sharks#index' 
  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end

Now, when users navigate to your application root, they will see a full listing of sharks, and have the opportunity to create a new shark entry, look at existing entries, and edit or delete given entries.

现在,当用户导航到您的应用程序根目录时,他们将看到鲨鱼的完整列表,并有机会创建新的鲨鱼条目,查看现有条目以及编辑或删除给定的条目。

Save the file and exit your editor when you are finished editing. If you used nano to edit the file, you can do so by pressing CTRL+X, Y, then ENTER

保存文件并在完成编辑后退出编辑器。 如果您使用nano来编辑文件,则可以通过按CTRL+XY ,然后按ENTER

You can now run your migrations with the following command:

现在,您可以使用以下命令运行迁移:

  • rails db:migrate

    rails db:migrate

You will see output confirming the migration.

您将看到输出确认迁移。

Start your Rails server once again. If you are working locally, type:

再次启动您的Rails服务器。 如果您在本地工作,请输入:

  • rails s

    滑轨

On a development server, type:

在开发服务器上,键入:

  • rails s --binding=your_server_ip

    rails s --binding = your_server_ip

Navigate to localhost:3000 if you are working locally, or http://your_server_ip:3000 if you are working on a development server.

如果在本地工作,请导航到localhost:3000如果在开发服务器上工作,则导航到http:// your_server_ip :3000

Your application landing page will look like this:

您的应用程序登录页面将如下所示:

To create a new shark, click on the New Shark link at the bottom of the page, which will take you to the sharks/new route:

要创建新的鲨鱼,请单击页面底部的“ New Shark”链接,这将带您进入sharks/new路线:

Let’s add some demo information to test our application. Input “Great White” into the Name field and “Scary” into the Facts field:

让我们添加一些演示信息来测试我们的应用程序。 在“ 名称”字段中输入“ Great White”,在“ 事实”字段中输入“ Scary”:

Click on the Create button to create the shark.

单击创建按钮创建鲨鱼。

This will direct you to the show route, which, thanks to the before_action filter, is set with the set_shark method, which grabs the id of the shark we’ve just created:

这将引导您到show路线,这要归功于before_action过滤器,它使用set_shark方法设置,该方法获取我们刚刚创建的鲨鱼的id

~/sharkapp/app/controllers/sharks_controller.rb
〜/ sharkapp / app / controllers / sharks_controller.rb
class SharksController < ApplicationController
  before_action :set_shark, only: [:show, :edit, :update, :destroy]

  . . . 

  def show
  end

  . . . 

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_shark
      @shark = Shark.find(params[:id])
    end
  . . .

You can test the edit function now by clicking Edit on your shark entry. This will take you to the edit route for that shark:

您现在可以通过在鲨鱼条目上单击“ 编辑”来测试编辑功能。 这将带您进入该鲨鱼的edit路线:

Change the facts about the Great White to read “Large” instead of “Scary” and click Update Shark. This will take you back to the show route:

将有关“伟大的白人”的facts更改为“大”而不是“可怕”,然后点击更新鲨鱼 。 这将带您回到show路线:

Finally, clicking Back will take you to your updated index view:

最后,单击上一步将带您进入更新的index视图:

Now that you have tested your application’s basic functionality, you can add some validations and security checks to make everything more secure.

现在,您已经测试了应用程序的基本功能,可以添加一些验证和安全检查,以使所有内容更加安全。

第5步-添加验证 (Step 5 — Adding Validations)

Your shark application can accept input from users, but imagine a case where a user attempts to create a shark without adding facts to it, or creates an entry for a shark that’s already in the database. You can create mechanisms to check data before it gets entered into the database by adding validations to your models. Since your application’s logic is located in its models, validating data input here makes more sense than doing so elsewhere in the application.

您的鲨鱼应用程序可以接受用户的输入,但是设想一种情况,用户尝试在不添加事实的情况下创建鲨鱼,或者为数据库中已有的鲨鱼创建条目。 您可以通过向模型添加验证来创建一种机制,以在数据进入数据库之前检查数据。 由于应用程序的逻辑位于其模型中,因此在这里验证数据输入比在应用程序中的其他地方进行验证更有意义。

Note that we will not cover writing validation tests in this tutorial, but you can find out more about testing by consulting the Rails documentation.

请注意,在本教程中我们不会涵盖编写验证测试,但是您可以通过参考Rails文档了解有关测试的更多信息。

If you haven’t stopped the server yet, go ahead and do that by typing CTRL+C.

如果尚未停止服务器,请继续并输入CTRL+C

Open your shark.rb model file:

打开您的shark.rb模型文件:

  • nano app/models/shark.rb

    纳米app / models / shark.rb

Currently, the file tells us that the Shark class inherits from ApplicationRecord, which in turn inherits from ActiveRecord::Base:

当前,该文件告诉我们Shark类继承自ApplicationRecord ,而ApplicationRecord继而继承自ActiveRecord::Base

~/sharkapp/app/models/shark.rb
〜/ sharkapp / app / models / shark.rb
class Shark < ApplicationRecord
end

Let’s first add some validations to our name field to confirm that the field is filled out and that the entry is unique, preventing duplicate entries:

首先,我们在name字段中添加一些验证,以确认该字段已填写并且该条目是唯一的,从而避免了重复的条目:

~/sharkapp/app/models/shark.rb
〜/ sharkapp / app / models / shark.rb
class Shark < ApplicationRecord
  validates :name, presence: true, uniqueness: true
end

Next, add a validation for the facts field to ensure that it, too, is filled out:

接下来,为facts字段添加验证,以确保也填写了它:

~/sharkapp/app/models/shark.rb
〜/ sharkapp / app / models / shark.rb
class Shark < ApplicationRecord
  validates :name, presence: true, uniqueness: true
  validates :facts, presence: true
end

We are less concerned here with the uniqueness of the facts, as long as they are associated with unique shark entries.

只要事实与唯一的鲨鱼条目相关联,我们在这里就不必担心事实的独特性。

Save and close the file when you are finished.

完成后保存并关闭文件。

Start up your server once again with either rails s or rails s --binding=your_server_ip, depending on whether you are working locally or with a development server.

再次使用rails srails s --binding= your_server_ip启动服务器,具体取决于您是在本地工作还是在开发服务器上工作。

Navigate to your application’s root at http://localhost:3000 or http://your_server_ip:3000.

导航到应用程序的根目录http://localhost:3000http:// your_server_ip :3000

Click on New Shark. In the form, add “Great White” to the Name field and “Big Teeth” to the Facts field, and then click on Create Shark. You should see the following warning:

单击“ 新鲨鱼” 。 在表单中,在“ 名称”字段中添加“ Great White”,在“ 事实”字段中添加“ Big Teeth”,然后单击“ 创建鲨鱼” 。 您应该看到以下警告:

Now, let’s see if we can check our other validation. Click Back to return to the homepage, and then New Shark once again. In the new form, enter “Tiger Shark” in the Name field, and leave Facts blank. Clicking Create Shark will trigger the following warning:

现在,让我们看看是否可以检查其他验证。 单击“上一步”返回首页,然后再次单击 新鲨鱼” 。 在新表单中,在“ 名称”字段中输入“ Tiger Shark”,然后将事实保留为空白。 单击创建鲨鱼将触发以下警告:

With these changes, your application has some validations in place to ensure consistency in the data that’s saved to the database. Now you can turn your attention to your application’s users and defining who can modify application data.

通过这些更改,您的应用程序将进行一些验证,以确保保存到数据库的数据的一致性。 现在,您可以将注意力转移到应用程序的用户上,并定义可以修改应用程序数据的人员。

步骤6 —添加身份验证 (Step 6 — Adding Authentication)

With validations in place, we have some guarantees about the data that’s being saved to the database. But what about users? If we don’t want any and all users adding to the database, then we should add some authentication measures to ensure that only permitted users can add sharks. In order to do this, we’ll use the http_basic_authenticate_with method, which will allow us to create a username and password combination to authenticate users.

有了验证,我们就可以保证将数据保存到数据库中。 但是用户呢? 如果我们不希望所有用户都添加到数据库中,则应添加一些身份验证措施,以确保只有允许的用户才能添加鲨鱼。 为此,我们将使用http_basic_authenticate_with方法 ,该方法将允许我们创建用户名和密码组合来对用户进行身份验证。

There are a number of ways to authenticate users with Rails, including working with the bcrypt or devise gems. For now, however, we will add a method to our application controller that will apply to actions across our application. This will be useful if we add more controllers to the application in the future.

有多种方法可以通过Rails对用户进行身份验证,包括使用bcryptdevise gem。 但是,现在,我们将向我们的应用程序控制器添加一个方法,该方法将应用于整个应用程序中的操作。 如果将来我们在应用程序中添加更多控制器,这将很有用。

Stop your server again with CTRL+C.

使用CTRL+C再次停止服务器。

Open the file that defines your ApplicationController:

打开定义您的ApplicationController的文件:

  • nano app/controllers/application_controller.rb

    纳米应用程序/控制器/application_controller.rb

Inside, you will see the definition for the ApplicationController class, which the other controllers in your application inherit from:

在内部,您将看到ApplicationController类的定义, ApplicationController中的其他控制器将从该类继承:

~/sharkapp/app/controllers/application_controller.rb
〜/ sharkapp / app / controllers / application_controller.rb
class ApplicationController < ActionController::Base
end

To authenticate users, we’ll use a hardcoded username and password with the http_basic_authenticate_with method. Add the following code to the file:

为了对用户进行身份验证,我们将通过http_basic_authenticate_with方法使用硬编码的用户名和密码。 将以下代码添加到文件中:

~/sharkapp/app/controllers/application_controller.rb
〜/ sharkapp / app / controllers / application_controller.rb
class ApplicationController < ActionController::Base
  http_basic_authenticate_with name: 'sammy', password: 'shark', except: [:index, :show]
end

In addition to supplying the username and password here, we’ve also restricted authentication by specifying the routes where it should not be required: index and show. Another way of accomplishing this would have been to write only: [:create, :update, :destroy]. This way, all users will be able to look at all of the sharks and read facts about particular sharks. When it comes to modifying site content, however, users will need to prove that they have access.

:除了这里提供的用户名和密码,我们还通过指定它应该被要求的路线限制的鉴别indexshow 。 实现此目的的另一种方法是only: [:create, :update, :destroy]编写only: [:create, :update, :destroy] 。 这样,所有用户都将能够查看所有鲨鱼并阅读有关特定鲨鱼的事实。 但是,在涉及修改网站内容时,用户将需要证明自己具有访问权限。

In a more robust setup, you would not want to hardcode values in this way, but for the purposes of demonstration, this will allow you to see how you can include authentication for your application’s routes. It also lets you see how Rails stores session data by default in cookies: once you authenticate on a specified action, you will not be required to authenticate again in the same session.

在更可靠的设置中,您不想以这种方式对值进行硬编码,但是出于演示的目的,这将使您看到如何为应用程序的路由包括身份验证。 它还使您可以看到Rails默认情况下如何将会话数据存储在cookie中:对指定操作进行身份验证后,将不需要在同一会话中再次进行身份验证。

Save and close app/controllers/application_controller.rb when you are finished editing. You can now test authentication in action.

完成编辑后,保存并关闭app/controllers/application_controller.rb 。 您现在可以测试实际的身份验证。

Start the server with either rails s or rails s --binding=your_server_ip and navigate to your application at either http://localhost:3000 or http://your_server_ip:3000.

使用rails srails s --binding= your_server_ip启动服务器,并通过http://localhost:3000http:// your_server_ip :3000导航到您的应用程序。

On the landing page, click on the New Shark button. This will trigger the following authentication window:

在登录页面上,单击“ New Shark”按钮。 这将触发以下身份验证窗口:

If you enter the username and password combination you added to app/controllers/application_controller.rb, you will be able to securely create a new shark.

如果输入添加到app/controllers/application_controller.rb的用户名和密码组合,则可以安全地创建新的鲨鱼。

You now have a working shark application, complete with data validations and a basic authentication scheme.

现在,您将有一个工作正常的Shark应用程序,其中包括数据验证和基本的身份验证方案。

结论 (Conclusion)

The Rails application you created in this tutorial is a jumping off point that you can use for further development. If you are interested in exploring the Rails ecosystem, the project documentation is a great place to start.

您在本教程中创建的Rails应用程序是一个起点,您可以将其用于进一步的开发。 如果您有兴趣探索Rails生态系统,那么项目文档是一个很好的起点。

You can also learn more about adding nested resources to your project by reading How To Create Nested Resources for a Ruby on Rails Application, which will show you how to build out your application’s models and routes.

您还可以通过阅读如何为Ruby on Rails应用程序创建嵌套资源来了解有关向项目中添加嵌套资源的更多信息,该文章将向您展示如何构建应用程序的模型和路由。

Additionally, you might want to explore how to set up a more robust frontend for your project with a framework such as React. How To Set Up a Ruby on Rails Project with a React Frontend offers guidance on how to do this.

另外,您可能想探索如何使用诸如React之类的框架为您的项目设置更强大的前端。 如何使用React Frontend设置Ruby on Rails项目提供了有关如何执行此操作的指南。

If you would like to explore different database options, you can also check out How To Use PostgreSQL with Your Ruby on Rails Application on Ubuntu 18.04, which walks through how to work with PostgreSQL instead of SQLite. You can also consult our library of PostgreSQL tutorials to learn more about working with this database.

如果您想探索不同的数据库选项,还可以查看Ubuntu 18.04上的PostgreSQL与Ruby on Rails应用程序一起使用的方法 ,它逐步介绍了如何使用PostgreSQL而不是SQLite。 您也可以查阅我们的PostgreSQL教程库,以了解有关使用该数据库的更多信息。

翻译自: https://www.digitalocean.com/community/tutorials/how-to-build-a-ruby-on-rails-application

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值