TK.
TK.

Reputation: 28153

Using "current_user" in models in Ruby on Rails

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.

Upvotes: 2

Views: 5340

Answers (2)

trptcolin
trptcolin

Reputation: 2340

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.

Upvotes: 0

Lee Jarvis
Lee Jarvis

Reputation: 16241

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.

Upvotes: 2

Related Questions