You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rails使用link_to修改数据库值时报Couldn't find Newcase无ID错误

报错根因

你遇到的Couldn't find Newcase without an ID错误核心是三个配置不匹配,路由没有捕获记录ID参数,视图传参路径错误,控制器更新逻辑也存在语法问题,修改方案如下:


1. 修正路由配置

当前你的patch/put路由没有预留ID占位符,无法传递要修改的Newcase记录ID,修改路由为:

get '/new', to:'newcase#new'
post '/new', to:'newcase#create'
# 新增带ID参数的路由,指定路由别名方便视图调用
patch '/newcases/:id/yesmarried', to: 'newcase#yesmarried', as: :yesmarried_newcase
put '/newcases/:id/yesmarried', to: 'newcase#yesmarried'

你之前错误使用了指向new动作的new_path,且将action参数放在HTML属性中不会被Rails路由识别,修改为新的路由助手传参:

<%= link_to 'yes', yesmarried_newcase_path(@newcase), class:"btn btn-lg rounded btn-warning", method: :put, "data-toggle" => "modal", 'data-target' => '#married-question', "data-bs-dismiss"=>"modal"  %>

注意:如果是Rails 7+版本,需要把method: :put替换为data: { turbo_method: :put }适配Turbo机制


3. 修正控制器yesmarried动作逻辑

你之前写的self.married = "yes"中self指代的是控制器实例而非Newcase记录,且修改后没有执行保存操作,修改为:

def yesmarried
  @newcase = Newcase.find(params[:id])
  @newcase.update(married: "yes")
  # 按需添加重定向逻辑,比如跳转回之前的页面:
  redirect_back fallback_location: root_path
end

额外注意点

你当前的create动作仅初始化了NewCase实例没有执行保存操作,提交表单后数据不会写入数据库,建议补充保存逻辑:

def create
  @newcase = NewCase.new(newcase_params)
  if @newcase.save
    # 保存成功后的跳转逻辑
    redirect_to some_path
  else
    render :new
  end
end

内容的提问来源于stack exchange,提问作者Ari Ticas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 12:57:01