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

Turbo Stream报Nil location错误:任务创建与状态切换问题排查

问题分析:Turbo Stream 返回时出现「Nil location provided. Can't build URI」错误

我有一个Project模型,关联多个Task模型。点击复选框可标记任务完成,期望此时更新任务样式并返回附加信息。任务本身能正常更新完成,但在返回turbo stream时,表单和复选框报错「Nil location provided. Can't build URI」,创建新任务时也出现相同错误。


相关代码

Task.html.erb

<div class="table-row" id="<%= dom_id task %>" data-id="<%= task.id %>">
  <div class="table-cell px-6 py-4 whitespace-nowrap text-md font-medium text-gray-800 dark:text-gray-200">
    <%= form_with(model: [@project, @task]) do |form| %>
      <%= form.check_box :completed,
        data: {
          id: task.id,
          action: "tasks#toggle"
        },checked: task.completed,
        class: "w-4 h-4 border-gray-300 rounded bg-gray-50 focus:ring-3 focus:ring-primary-300 dark:focus:ring-primary-600 dark:ring-offset-gray-800 dark:bg-gray-700 dark:border-gray-600" %>
    <% end %>
  </div>
  <div class="table-cell px-6 py-4 whitespace-nowrap text-md text-gray-800 dark:text-gray-200">
      <div class="text-base font-semibold text-gray-900 dark:text-white"><%= task.description %>
      </div>
      <div class="text-sm font-normal text-gray-500 dark:text-gray-400">
        <% if task.completed? %>
          <div class="text-base font-normal text-gray-500 dark:text-gray-400">Completed: <%= time_ago_in_words(task.updated_at) %> ago
          </span> by 
          <span class="font-weight-normal ml-2"><%= task.user.email %>
          </div>
        <% end %>
      </div>
  </div>
  <div class="table-cell px-6 py-4 whitespace-nowrap text-right text-md font-medium">
      <div class="flex justify-end">
          <button type="button" data-modal-toggle="product-modal" class="inline-flex items-center px-3 py-2 text-sm font-medium text-center text-white bg-primary-700 rounded-lg hover:bg-primary-800 focus:ring-4 focus:ring-primary-300 dark:bg-primary-600 dark:hover:bg-primary-700 dark:focus:ring-primary-800">
              <svg class="w-5 h-5 mr-2" fill="currentColor" viewBox="0 0 20 20"
                  xmlns="http://www.w3.org/2000/svg">
                  <path d="M17.414 2.586a2 2 0 00-2.828 0L7 10.172V13h2.828l7.586-7.586a2 2 0 000-2.828z"></path>
                  <path fill-rule="evenodd" d="M2 6a2 2 0 012-2h4a1 1 0 010 2H4v10h10v-4a1 1 0 112 0v4a2 2 0 01-2 2H4a2 2 0 01-2-2V6z" clip-rule="evenodd"></path>
              </svg>
              Edit item
          </button>
          <button type="button" data-modal-toggle="delete-product-modal" class="inline-flex items-center px-3 py-2 text-sm font-medium text-center text-white bg-red-700 rounded-lg hover:bg-red-800 focus:ring-4 focus:ring-red-300 dark:focus:ring-red-900">
              <svg class="w-5 h-5 mr-2" fill="currentColor" viewBox="0 0 20 20"
                  xmlns="http://www.w3.org/2000/svg">
                  <path fill-rule="evenodd" d="M9 2a1 1 0 00-.894.553L7.382 4H4a1 1 0 000 2v10a2 2 0 002 2h8a2 2 0 002-2V6a1 1 0 100-2h-3.382l-.724-1.447A1 1 0 0011 2H9zM7 8a1 1 0 012 0v6a1 1 0 11-2 0V8zm5-1a1 1 0 00-1 1v6a1 1 0 102 0V8a1 1 0 00-1-1z" clip-rule="evenodd"></path>
              </svg>
              Delete item
          </button>
      </div>
  </div>
</div>

project/show.html.erb

<%= turbo_stream_from "tasks" %>
<div class="overflow-hidden">
  <div class="table border-collapse table-auto w-full divide-y divide-gray-200 dark:divide-gray-700">
    
    <div class="table-row-group divide-y divide-gray-200 bg-white dark:divide-gray-700 dark:bg-gray-800" 
    id="tasks" data-controller="drag" data-drag-url="/projects/<%= @project.id %>/tasks/:id/move">
        <%= render @tasks.order('position asc') %>
    </div>
  </div>
</div>

Task.rb

class Task < ApplicationRecord
  belongs_to :project
  belongs_to :user
  acts_as_list
  after_create_commit {broadcast_prepend_to "tasks"}
end

TasksController.rb

class TasksController < ApplicationController
before_action :set_task, except: [:create]
before_action :set_project, except: [:toggle]

def index
  @tasks = Task.all
  @task = Task.new
end

def show
end

def new
  @task = Task.new
end

def edit
end

def create
  @task = @project.tasks.build(task_params)
  @task.user_id = current_user.id

  respond_to do |format|
    if @task.save
      format.turbo_stream
      format.html { redirect_to project_task_path(@project, @task), notice: "Task was successfully created." }
      format.json { render :show, status: :created, location: @task }
    else
      format.html { render :new, status: :unprocessable_entity }
      format.json { render json: @task.errors, status: :unprocessable_entity }
    end
  end
end

def update
  respond_to do |format|
    if @task.update(task_params)
      format.html { redirect_to project_task_path(@project, @task), notice: "Task was successfully updated." }
      format.json { render :show, status: :ok, location: @task }
    else
      format.html { render :edit, status: :unprocessable_entity }
      format.json { render json: @task.errors, status: :unprocessable_entity }
    end
  end
end

def destroy
  @task.destroy

  respond_to do |format|
    format.html { redirect_to tasks_url, notice: "Task was successfully destroyed." }
    format.json { head :no_content }
  end
end

def toggle
  @task = Task.find(params[:id])
  @task.update(completed: params[:completed])
end

def move
  @task.insert_at(params[:position].to_i)
  head :ok
end

private
  def set_task
    @task = Task.find(params[:id])
  end

  def set_project
  @project = Project.find(params[:project_id])
  end

  def task_params
    params.require(:task).permit(:title, :position, :description, :project_id, :user_id, :status, :completed)
  end
end

错误原因分析

  1. toggle动作缺少必要实例变量与Turbo响应
    任务模板里的form_with(model: [@project, @task])依赖@project变量生成表单URL,但toggle方法中只查询了@task,未设置@project。当Turbo尝试重新渲染任务部分时,@project为nil,导致无法构建URI,抛出错误。同时toggle没有处理Turbo Stream响应,默认会尝试渲染模板或重定向,进一步引发问题。

  2. 复选框的表单配置错误
    复选框的data-action: "tasks#toggle"不符合Turbo的语法规范,无法正确触发指定动作,表单提交的目标路由不正确,也会导致URL构建失败。

  3. 创建任务的Turbo Stream上下文缺失
    虽然create动作有format.turbo_stream,但默认渲染的模板可能需要@project变量来生成任务里的表单URL,如果模板中未传递该变量,同样会触发nil位置错误。


修复方案

1. 完善toggle动作

修改TasksController的toggle方法,添加@project变量并处理Turbo Stream响应:

def toggle
  @task = Task.find(params[:id])
  @project = @task.project # 关键:设置@project
  @task.update(completed: params[:completed])

  respond_to do |format|
    format.turbo_stream do
      render turbo_stream: turbo_stream.replace(
        @task, 
        partial: "tasks/task", 
        locals: { task: @task, project: @project }
      )
    end
    format.html { redirect_to project_path(@project), notice: "任务已更新" }
  end
end

2. 修正复选框表单配置

修改Task.html.erb中的表单,指定正确的路由和提交方式:

<div class="table-cell px-6 py-4 whitespace-nowrap text-md font-medium text-gray-800 dark:text-gray-200">
  <%= form_with(model: task, url: toggle_project_task_path(task.project, task), method: :patch) do |form| %>
    <%= form.check_box :completed,
      onchange: "this.form.submit()",
      checked: task.completed,
      class: "w-4 h-4 border-gray-300 rounded bg-gray-50 focus:ring-3 focus:ring-primary-300 dark:focus:ring-primary-600 dark:ring-offset-gray-800 dark:bg-gray-700 dark:border-gray-600" %>
  <% end %>
</div>

同时在routes.rb中添加toggle路由:

resources :projects do
  resources :tasks do
    patch :toggle, on: :member
  end
end

3. 确保创建任务的Turbo Stream上下文正确

创建app/views/tasks/create.turbo_stream.erb模板,传递必要的变量:

<%= turbo_stream.prepend "tasks", partial: "tasks/task", locals: { task: @task, project: @project } %>

4. 修正模型广播(可选)

如果需要创建任务的广播也能正确渲染,修改Task模型的回调:

after_create_commit { broadcast_prepend_to "tasks", locals: { project: self.project } }

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 02:55:27