Ruby on Rails:new/create动作数据保存与show页面显示问题排查
问题排查与解决方案
1. 修复核心路由问题
你的routes.rb未包含:create动作,导致表单提交时无对应路由处理请求,这是数据无法保存的关键原因。修改routes.rb:
Rails.application.routes.draw do root "articles#index" resources :articles, only: [:edit, :update, :show, :destroy, :index, :new, :create] end
若需要完整的RESTful路由,可简化为:
Rails.application.routes.draw do root "articles#index" resources :articles end
2. 完善控制器的创建逻辑
当前create方法未处理保存失败场景(如模型验证不通过),添加失败分支逻辑:
def create @article = Article.new(article_params) if @article.save redirect_to @article # 保存成功跳转到详情页 else render :new # 保存失败返回新建页,保留用户已输入内容 end end
3. 可选:补充模型验证(推荐)
若需确保数据合法性,在app/models/article.rb中添加验证规则:
class Article < ApplicationRecord validates :title, presence: true validates :description, presence: true end
4. 确认详情页展示逻辑
你的show.html.erb已正确绑定@article的属性,只要数据保存成功,跳转到该页面后即可正常展示标题和描述内容。
验证步骤
- 重启Rails服务器
- 访问
/articles/new填写表单并提交 - 保存成功则自动跳转至
/articles/:id页面,展示提交的数据;验证失败则留在新建页,可根据提示修正输入。
内容的提问来源于stack exchange,提问作者Afaq Shahid Khan
相关产品推荐
相关产品推荐

