在rails入门博客中遇到的问题

1,新建一个资源数据库

Rails.application.routes.draw do
 
   resources :articles
 
   root 'welcome#index'
end

2,执行生成rest风格的的动做浏览器

$ bin/rake routesapp

      Prefix Verb   URI Pattern                  Controller#Actionspa

    articles GET    /articles(.:format)          articles#indexrest

             POST   /articles(.:format)          articles#createcode

 new_article GET    /articles/new(.:format)      articles#neworm

edit_article GET    /articles/:id/edit(.:format) articles#edit对象

     article GET    /articles/:id(.:format)      articles#show资源

             PATCH  /articles/:id(.:format)      articles#update字符串

             PUT    /articles/:id(.:format)      articles#update

             DELETE /articles/:id(.:format)      articles#destroy

        root GET    /                            welcome#index

3,一段输出代码

render plain: params[:article].inspect

inspect相似于toString,就是把参数的信息打印在页面上

render 方法接受一个简单的 Hash 为参数,这个 Hash 的键是 plain,对应的值为 params[:article].inspectparams 方法表示经过表单提交的参数

4,新建模型

$ bin/rails generate model Article title:string text:text

5,执行数据库迁移,就是相似于把对象对应到数据库中的相应表中

db:migrate

6,用 render 方法才能在保存失败后把 @article 对象传给 new 动做的视图。渲染操做和表单提交在同一次请求中完成;而 redirect_to 会让浏览器发起一次新请求

7,数据验证

@article.errors.any? 检查是否有错误,若是有错误,使用 @article.errors.full_messages 显示错误

pluralize 是 Rails 提供的帮助方法,接受一个数字和字符串做为参数。若是数字比 1 大,字符串会被转换成复数形式

<%= pluralize(@article.errors.count, "error") %>这段代码显示的是一共有几个错误的信息

8,在app/models/article.rb中写入校验的规则

class Article < ActiveRecord::Base
   validates :title , presence: true ,
                     length: { minimum: 5 }
end

presence:true;不能为空。length:{minimum:5}最少多少个字

相关文章
相关标签/搜索