Ruby on Rails 入门

471 阅读3分钟

1、配置 gem 源

1、 gem 删除默认源命令

打开命令行(win+r -> cmd 快速打开命令行),输入命令

gem sources --remove https://rubygems.org/

2、gem 添加国内源

gem sources -a https://gems.ruby-china.com/

3、检测方法

gem sources -l

image.png

2、安装 Rails

C:> gem install rails

image.png

检查是否安装完成

rails -v

image.png

3、rails 项目快速上手

1、创建

rails new demo

image.png

2、修改 Gemfile源

调整第一行,如下图

image.png

3、进行项目目录重新安装依赖

cd demo
bundle

如图所示:

image.png

4、各个目录作用

image.png

  • app:存放web应用的控制器、视图、模型、helpers等,开发主要集中在这里

  • bin*:各种脚本

  • config:路由、数据库等的配置文件

  • db:数据库的schema和数据库的迁移文件

  • log:日志文件

  • package.json:npm包记录,使用yarn管理

  • public:静态文件

  • test:测试

5、启动项目

rails server

image.png

使用 rails server 命令启动服务器即可在本地3000端口访问到服务

image.png

4、替换首页

1、idea 安装ruby插件

image.png

2、命令生成控制器hello

rails generate controller hello

image.png

3、修改 config/routes.rb 路由

Rails.application.routes.draw do
  get  "hello/index"
  root "hello#index"
end

这里定义了路由hello/index,并且使用root方法将首页修改为了hello控制器下的index方法,也就是两路由的控制器一致。

4、定义控制器

class HelloController < ApplicationController
  def index
  end
end

5、定义视图

rails足够智能可以自己在视图文件夹寻找名为 index.html.erb 的视图文件,将视图文件写入以下内容

image.png

此时,浏览器中打开 / 和 /hello/index/ 路径都将返回同样的内容

image.png

6、新增文章

1、生成数据库模型:

rails generate model Article title:string content:text

image.png

2、迁移数据库:

rails db:migrate

image.png

db控制台操作

rails console

image.png

1、新增数据
 article = Article.new(title:"hello",content:"java")

image.png

2、获取所有数据
Article.all

image.png

3、查询一条数据
Aritle.find(7)

image.png

3、生成控制器:

rails generate controller Articles

image.png

4、配置articles的路由:

Rails.application.routes.draw do
  resources :articles
end

image.png

使用 rails routes 命令查看当前的路由配置:

image.png

很明显,从这里可以看到每个路由应该对应的控制器方法,这是一个典型的RESTful api的配置。

5、创建视图文件

按照上文中的方法创建好 new.html.erb 文件和 new 方法,在 new.html.erb 文件中写入:

<h2>new article</h2>

<%= form_with(scope: :article, url: articles_path, local: true) do |form|  %>
  <p>
    <%= form.label :title %> <br>
    <%= form.text_field :title %>
  </p>
  <p>
    <%= form.label :content %> <br>
    <%= form.text_area :content %>
  </p>

  <%= form.submit %>
<% end %>

image.png

form_with 方法默认是提交到当前路由,通过url字段将其定义为post到 /articles 路径。

此时访问 /articles/new 路径可以看到表单:

image.png

此时我们需要定义提交之后的处理路径,从上面的路由配置中我们可以知道对应于 create 方法

提交的表单数据与捕获的路由参数一起放入参数 Hash 中。因此,create 操作可以通过 params [:article ][:title ]访问提交的标题,通过 params [:article][:body]访问提交的主体。我们可以单独地将这些值传递给 Article.new,但是这样做会非常冗长,而且可能容易出错。当我们添加更多字段时,情况会变得更糟。

相反,我们将传递一个包含值的 Hash。但是,我们仍然必须指定哈希中允许的值。否则,恶意用户可能会提交额外的表单字段并覆盖私有数据。事实上,如果我们将未过滤的参数[:article ]散列直接传递给 Article.new,Rails 将引发一个 ForbiddenAttributesError 来提醒我们有关问题。因此,我们将使用一个称为强参数的 Rails 特性来过滤参数。可以把它看作是 params 的强类型。

6、编写控制器Action

class ArticlesController < ApplicationController

      def create
        @article = Article.new(article_params)
        @article.save

        redirect_to @article
      end

    private
    def article_params
      params.require(:article).permit(:title, :content)
    end
end

此时提交表单,可以看到报错:

image.png

于是我们定义show方法:

def show
  @article = Article.find(params[:id])
end

定义相应的视图文件 show.html.erb :

<h2>Show article</h2>

<p>
  title: <br> <%= @article.title %>
</p>

<p>
  content: <br> <%= @article.content %>
</p>

此时提交表单则直接跳转到show视图定义:

image.png

文章的列举

我们利用 index action 列举所有的article,定义 index 方法

def index
  @article = Article.all
end

定义视图:

<h2>List all Articles </h2>

<%= link_to "new article", new_article_path %>

<% @article.each do |a| %>
  <p>
    title: <br> <%= a.title %>
  </p>
  <p>
    content: <br> <%= a.content %>
  </p>

<% end %>

此时访问 /articles 路径可以看到

image.png

7、参数校验

正如我们所看到的,创建资源是一个多步骤的过程。处理无效的用户输入是该过程的另一个步骤。Rails 提供了一个称为验证的特性来帮助我们处理无效的用户输入。验证是在保存模型对象之前检查的规则。如果任何检查失败,保存将被中止,并且适当的错误消息将被添加到模型对象的 error 属性中。

1、修改实体对象

class Article < ApplicationRecord
  validates :title, presence: true
  validates :content, presence: true, length: { minimum: 10 }
end

验证就绪后,让我们修改 app/views/article/new.html.erb 以显示 title 和 body 的任何错误消息:

2、调整添加的视图

<h1>New Article</h1>

<%= form_with model: @article do |form| %>
  <div>
    <%= form.label :title %><br>
    <%= form.text_field :title %>
    <% @article.errors.full_messages_for(:title).each do |message| %>
      <div><%= message %></div>
    <% end %>
  </div>

  <div>
    <%= form.label :content %><br>
    <%= form.text_area :content %><br>
    <% @article.errors.full_messages_for(:content).each do |message| %>
      <div><%= message %></div>
    <% end %>
  </div>

  <div>
    <%= form.submit %>
  </div>
<% end %>

为了理解所有这些操作是如何一起工作的,让我们再来看看新的和创建控制器操作:

def new
  @article = Article.new
end

def create
  @article = Article.new(article_params)

  if @article.save
    redirect_to @article
  else
    render :new, status: :unprocessable_entity
  end
end

3、结果验证

结果如下:

image.png

8、更新文章

1、新增控制器修改

  def edit
    @article = Article.find(params[:id])
  end

  def update
    @article = Article.find(params[:id])

    if @article.update(article_params)
      redirect_to @article
    else
      render :edit, status: :unprocessable_entity
    end
  end

2、部分共享视图

因为代码是相同的,所以我们要把它分解成一个共享视图,叫做局部视图。让我们使用以下内容创建 app/views/article/_ form.html.erb

<%= form_with model: article do |form| %>
  <div>
    <%= form.label :title %><br>
    <%= form.text_field :title %>
    <% article.errors.full_messages_for(:title).each do |message| %>
      <div><%= message %></div>
    <% end %>
  </div>

  <div>
    <%= form.label :content %><br>
    <%= form.text_area :content %><br>
    <% article.errors.full_messages_for(:content).each do |message| %>
      <div><%= message %></div>
    <% end %>
  </div>

  <div>
    <%= form.submit %>
  </div>
<% end %>

新增的视图修改如下: app/views/articles/new.html.erb

<h1>New Article</h1>

<%= render "form", article: @article %>

编辑的视图内容如下: app/views/articles/edit.html.erb

<h1>Edit Article</h1>

<%= render "form", article: @article %>

app/views/articles/show.html.erb

<h1><%= @article.title %></h1>

<p><%= @article.content %></p>

<ul>
  <li><%= link_to "Edit", edit_article_path(@article) %></li>
</ul>

3、结果验证

image.png

9、参考文档

guides.rubyonrails.org/getting_sta…