Ruby on Rails——一个完整的例子(六)

这一节我们来学习一下怎样更新我们创建的博客。

既然要做变更的操作,我们首先要在controller中添加update方法,update方法与create方法基本是一样的,不同的是create创建的是一个新的article,而update要有一个更新的对象,所以在create中用到的是Article.new,而在update中用到的则是Article.find,根据article的id来进行查找。

def create

  @article = Article.new(article_params)

 

  if @article.save

    redirect_to @article

  else

    render 'new'

  end

end

 

def update

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

 

  if @article.update(article_params)

    redirect_to @article

  else

    render 'edit'

  end

end

 

private

  def article_params

    params.require(:article).permit(:title, :text)

  end

我们还需要创建一个edit页面,而edit页面与new页面的内容也有几分相似,不同的是,edit页面通过id已经获取了article的既存信息了。

<h1>Edit article</h1>

 

<%= form_with(model: @article, local: true) do |form| %>

 

  <% 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>

    <%= form.label :title %><br>

    <%= form.text_field :title %>

  </p>

 

  <p>

    <%= form.label :text %><br>

    <%= form.text_area :text %>

  </p>

 

  <p>

    <%= form.submit %>

  </p>

 

<% end %>

 

<%= link_to 'Back', articles_path %>

 与此相对应,我们还需要在controller中添加一个edit方法,这个方法中不要太多操作,只需要根据article id将编辑对象找到就可以了。

def new

  @article = Article.new

end

 

def edit

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

end

 

def create

  @article = Article.new(article_params)

 

  if @article.save

    redirect_to @article

  else

    render 'new'

  end

end

 根据前面的讲解内容在相关view中加入一些迁移语句,我们就把article的更新功能实现了。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值