前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Rails MVC 和 CRUD(11)

Rails MVC 和 CRUD(11)

作者头像
franket
发布2021-11-25 16:20:55
2570
发布2021-11-25 16:20:55
举报
文章被收录于专栏:技术杂记技术杂记

列表页面多出来两个链接,点击 【New article】

rails20.png
rails20.png

成功跳转到了添加页面,随便输入点什么,提交

rails21.png
rails21.png

自动跳转到了显示页面,点击【Back】

rails22.png
rails22.png

跳转回了所有列表页面

rails23.png
rails23.png

Tip: 之所以每做一次修改都能直接生效,是因为在开发模式下(默认),每次请求 Rails 都会自动重新加载程序,因此修改之后无需重启服务器


数据验证

我们常常有对输入进行校验的需求,以避免接受到了无效或不合规范的数据

代码语言:javascript
复制
[root@h202 blog]# vim app/models/article.rb
[root@h202 blog]# cat app/models/article.rb
class Article < ActiveRecord::Base
  validates :title, presence: true, length: { minimum: 5 }
end
[root@h202 blog]# vim app/controllers/articles_controller.rb 
[root@h202 blog]# cat app/controllers/articles_controller.rb 
class ArticlesController < ApplicationController
  def new
    @article = Article.new
  end
  def create
#    render plain: params[:article].inspect
#    @article = Article.new(params[:article])
     @article = Article.new(article_params)
     
     if @article.save
       redirect_to @article
     else
       render 'new'
     end
  end
  def show
    @article = Article.find(params[:id])
  end
  def index
    @articles = Article.all
  end
  private
    def article_params
        params.require(:article).permit(:title,:text)
    end
end
[root@h202 blog]# vim app/views/articles/new.html.erb 
[root@h202 blog]# cat app/views/articles/new.html.erb 
<h1>Test blog http://soft.dog/</h1>

<%= form_for :article, url: articles_path do |f| %>

 <% if @article.errors.any? %>
  <div id="error_explanation">
    <h2><%= pluralize(@article.errors.count, "error") %> prohibited
      this article from being saved:</h2>
    <ul>
    <% @article.errors.full_messages.each do |msg| %>
      <li><%= msg %></li>
    <% end %>
    </ul>
  </div>
  <% end %>


  <p>
    <%= f.label :title %><br>
    <%= f.text_field :title %>
  </p>
 
  <p>
    <%= f.label :text %><br>
    <%= f.text_area :text %>
  </p>
 
  <p>
    <%= f.submit %>
  </p>
<% end %>

 
<%= link_to 'Back', articles_path %>
[root@h202 blog]#  

本文系转载,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文系转载前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 数据验证
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档