我想了解设计 current_user 方法是如何工作的,因为我想将它推广到其他模型,这些模型将允许诸如 current_forum 或 current_forum_thread 之类的代码。
更具体地说,我正在尝试在 Rails 中实现一个聊天论坛。我有一个页面显示特定讨论线程的所有帖子(目前没有)。同一页面嵌入了新的帖子表单。调试(参数)显示:
action: show
controller: discussions
forum_id: '1'
id: '1'
discussion: !ruby/object:Discussion
attributes:
id: 1
title: first discussion (thread)
forum_id: 1
因此帖子 Controller 中的创建方法应该知道讨论 ID 是什么。然而, Controller 中的这段代码不起作用。
1. @discussion = Discussion.find(params[:id])
2. @post = @discussion.posts.new(params[:post])
3. if @post.save
4. flash[:success] = "Discussion post created!"
5. redirect_to '#'
6. else
7. render '#'
8. end
第 1 行引发错误:
Couldn't find Discussion without an ID
此外,经检查发现@discussion 变量始终为 NIL。
最佳答案
我认为它更像是一个辅助函数,devise 的方法是通过 session 获取 ID,但您也可以通过 params 哈希执行相同的操作, 即
module ApplicationHelper
def current_forum_thread
Thread.find(params[:id])
end
end
这对你有用吗?
关于ruby-on-rails - 如何设计 current_user 工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14548293/