更新,删除
class ArticlesController < ApplicationController
def index
@articles = Article.all
end
def show
@article = Article.find(params[:id])
end
def new
@article = Article.new
end
def create
@article = Article.new(article_params)
if @article.save
redirect_to @article
else
render :new, status: :unprocessable_entity
end
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, status: :unprocessable_entity
end
end
def destroy
@article = Article.find(params[:id])
@article.destroy
redirect_to root_path
end
private
def article_params
params.require(:article).permit(:title, :body)
end
end
update
<%= form_with model: article do |form| %>
<%= form.label :title %>
<%= form.text_field :title %> <% article.errors.full_messages_for(:title).each do |message| %>
<%= form.text_field :title %> <% article.errors.full_messages_for(:title).each do |message| %>
<%= message %>
<% end %>
<%= form.label :body %>
<%= form.text_area :body %>
<% article.errors.full_messages_for(:body).each do |message| %>
<%= form.text_area :body %>
<% article.errors.full_messages_for(:body).each do |message| %>
<%= message %>
<% end %>
<%= form.submit %>
<% end %>
new.index
destroy
<%= @article.title %>
<%= @article.body %>
- <%= link_to "Edit", edit_article_path(@article) %>
- <%= link_to "Destroy", article_path(@article), method: :delete, data: { confirm: "Are you sure?" } %>