Using “current_user” in models in Ruby on Rails

大城市里の小女人 提交于 2020-01-02 08:54:47

问题


I'm using Devise and it offers "current_user" method in helpers, so that I can use in views and controllers.

However now I'd like to access to the "current_user" method in the models. Here's what I have in controllers now.

def create
  set_email_address(params[:email_address])
  Comment.new(params[:content], set_email_address)
  # [snip]
end

private
def set_email_address(param_email)
  if current_user
    @email_address = current_user.email
  else
    @email_address = param_email
  end
end

I would like to move the "set_email_address" to a model because I think that is a logic and should be handed in the model. I'm planning on hooking up this method with one of the Rails callbacks.


回答1:


In all honesty, this answer pretty much sums it up. This doesn't belong in Model logic at all. As the other answer also says though, you can and should pass the current_user value from the controller if you'd like to use it inside your model.




回答2:


The current_user is request- or session- bound data, and I'd encourage you to keep it out of the model. That's really what the controller is for. However, it's not a bad idea to move it out of this particular controller if you feel like it's something that should be available in other places. In that case, you might move it up to ApplicationController, or better yet, a module that you can mix into this controller.

You'd still need to separate out your @email_address-setting behavior from the decision about which email address to use, since setting that instance variable doesn't make sense in the model's context.



来源:https://stackoverflow.com/questions/4140703/using-current-user-in-models-in-ruby-on-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!