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

如何在StimulusReflex中获取current_user?字段赋值问题求助

在StimulusReflex中获取current_user并设置lastUpdatedBy字段的解决方案

看起来你遇到的核心问题是StimulusReflex的Reflex类默认不会直接提供current_user方法,另外还有个容易忽略的字段名大小写问题,我来一步步帮你解决:

1. 确保Reflex类继承自ApplicationReflex

首先,你的TodoReflex类应该继承自动生成的ApplicationReflex,而不是直接继承StimulusReflex::Reflex。ApplicationReflex是所有自定义Reflex的基类,默认已经帮你处理了和Rails会话、用户上下文的关联:

class TodoReflex < ApplicationReflex
  def toggle
    # 你的逻辑代码
  end
end

2. 为ApplicationReflex添加current_user委托

如果你的ApplicationReflex还没有配置current_user,需要在app/reflexes/application_reflex.rb里添加委托,让Reflex类能从connection对象中获取当前用户:

class ApplicationReflex < StimulusReflex::Reflex
  # 把current_user委托给connection对象,这样所有子类Reflex都能直接用current_user
  delegate :current_user, to: :connection
end

StimulusReflex的connection对象和Rails控制器的上下文是共享的,所以这里能拿到Devise(或你用的认证系统)提供的current_user。

3. 修正字段名的大小写问题

注意到你代码里用的是lastUpdatedBy,但Rails遵循蛇形命名约定,数据库字段和模型属性一般是last_updated_by。如果你的数据库字段是蛇形命名,驼峰写法会导致赋值失败。修正后的代码应该是:

def toggle
  todo = Todo.find(element.dataset[:id])
  todo.update(
    completed_at: (todo.completed_at? ? nil : Time.current),
    last_updated_by: current_user
  )
end

同时要确保你的Todo模型里已经正确定义了last_updated_by这个关联字段(通常是指向users表的外键)。

完整修正后的代码示例

class TodoReflex < ApplicationReflex
  def toggle
    todo = Todo.find(element.dataset[:id])
    todo.update(
      completed_at: (todo.completed_at? ? nil : Time.current),
      last_updated_by: current_user
    )
  end
end

这样修改后,你应该就能成功把current_user赋值给last_updated_by字段了。本质上就是让Reflex类能访问到Rails的用户上下文,同时遵循Rails的命名规范避免属性赋值失败。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 14:22:28