定义 update 方法,并且添加 edit 链接和 show 链接
代码语言:javascript复制[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 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'
end
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/index.html.erb
[root@h202 blog]# cat app/views/articles/index.html.erb
<h1>Link test!!!!</h1>
<%= link_to 'My Blog', controller: 'articles' %>
<%= link_to 'New article', new_article_path %>
<table>
<tr>
<th>Title</th>
<th>Text</th>
</tr>
<% @articles.each do |article| %>
<tr>
<td><%= article.title %></td>
<td><%= article.text %></td>
<td><%= link_to 'Show', article_path(article) %></td>
<td><%= link_to 'Edit', edit_article_path(article) %></td>
</tr>
<% end %>
</table>
[root@h202 blog]#
[root@h202 blog]# vim app/views/articles/show.html.erb
[root@h202 blog]# cat app/views/articles/show.html.erb
<p>
<strong>Title:</strong>
<%= @article.title %>
</p>
<p>
<strong>Text:</strong>
<%= @article.text %>
</p>
<%= link_to 'Back', articles_path %>
| <%= link_to 'Edit', edit_article_path(@article) %>
[root@h202 blog]#