如何在StimulusReflex中获取current_user?字段赋值问题求助
看起来你遇到的核心问题是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

