这一节我们来学习一下怎样更新我们创建的博客。
既然要做变更的操作,我们首先要在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的更新功能实现了。
