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, notice: "文章创建成功"
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, notice: "文章已更新"
else
render :edit, status: :unprocessable_entity
end
end
def destroy
@article = Article.find(params[:id])
@article.destroy
redirect_to articles_path, notice: "文章已删除", status: :see_other
end
private
def article_params
params.require(:article).permit(:title, :body)
end
end
class ArticlesController < ApplicationController
before_action :set_article, only: [:show, :edit, :update, :destroy]
def show
end
def edit
end
def update
if @article.update(article_params)
redirect_to @article, notice: "文章已更新"
else
render :edit, status: :unprocessable_entity
end
end
def destroy
@article.destroy
redirect_to articles_path, notice: "文章已删除", status: :see_other
end
private
def set_article
@article = Article.find(params[:id])
end
def article_params
params.require(:article).permit(:title, :body)
end
end
show 和 edit 方法体直接空了——回调已经备好数据,Rails 按约定渲染同名视图。
步骤 4:一个动作同时服务 HTML 和 JSON
def index
@articles = Article.all
respond_to do |format|
format.html # 渲染 index.html.erb
format.json { render json: @articles } # /articles.json 返回 JSON
end
end
验证:
curl http://localhost:3000/articles.json
这就是 Rails 全栈模式的弹性:同一套控制器既能渲染页面,也能当 API 用。当然,纯 API 项目可以用 rails new myapp --api 生成精简版控制器基类。