如何获取模型观察者中的current_user?
给定以下模型:
Room (id, title)
RoomMembers (id, room_id)
RoomFeed, also an observer
当更新房间标题时,我想创建一个 RoomFeed 项目,显示进行更新的用户是谁。
@room.update_attributes(:title => "This is my new title")
问题出在我的 RoomFeed 观察者身上:
def after_update(record)
# record is the Room object
end
我无法获取刚刚进行更新的人的 user.id。我该如何去做呢?有没有更好的方法来进行更新以便我获得 current_user?
Given the following models:
Room (id, title)
RoomMembers (id, room_id)
RoomFeed, also an observer
When a Room title is updated, I want to create a RoomFeed item, showing who the user is who made the update.
@room.update_attributes(:title => "This is my new title")
Problem is in my observer for RoomFeed:
def after_update(record)
# record is the Room object
end
The is no way for me to get the user.id of the person who just made the update. How do I go about doing that? is there a better way to do the update so I get the current_user?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我认为您正在寻找的是观察者内的 room.updated_by 。如果您不想保留updated_by,只需将其声明为attr_accessor即可。在推送更新之前,请确保将 current_user 分配给 Updated_by,可能来自您的控制器。
I think what you are looking for is, room.updated_by inside your observer. If you don't want to persist the updated_by, just declare it as an attr_accessor. Before you push the update, make sure you assign the current_user to updated_by, may be from you controller.
这是一个典型的“关注点分离”问题。
current_user 位于控制器中,Room 模型应该对此一无所知。也许 RoomManager 模型可以处理谁在更改门上的名字……
同时,可以快速完成更改。肮脏的解决方案是在 Room.rb 中抛出一个(非持久)属性来处理 current_user....
并在更新 @room 时在参数中传递 current_user 。
这样你就找到了罪魁祸首! :
This is a typical "separation of concern" issue.
The current_user lives in the controller and the Room model should know nothing about it. Maybe a RoomManager model could take care of who's changing the name on the doors...
Meanwhile a quick & dirty solution would be to throw a (non persistant) attribute at Room.rb to handle the current_user....
and pass your current_user in the params when updating @room.
That way you've got the culprit! :
创建以下内容
然后使用...
请记住,当从非 Web 请求(如 rake 任务)调用您的类时,不保证会设置该值,因此您应该检查
.nil?
Create the following
Then use...
Remember that the value isn't guaranteed to be set when your class is called from non-web requests, like rake tasks, so you should check for
.nil?
我想这是一个更好的方法
http://rails-bestpractices。 com/posts/47-fetch-current-user-in-models
I guess this is a better approach
http://rails-bestpractices.com/posts/47-fetch-current-user-in-models
更新 user.rb
更新 application_controller.rb
然后您可以在任何地方通过
User.current
获取登录用户。我正在使用这种方法来准确地在观察者中访问用户。Update user.rb
Update application_controller.rb
Then you can get logged user by
User.current
anywhere. I'm using this approach to access user exactly in observers.