user2419316
user2419316

Reputation: 331

model not recognizing current_user or User.current in rails?

As the title states, all my other models are able to recognize User.current in my models but in one of my new models I'm trying to do the following and can't get it working. Actually I think it does work but it states it doesn't have that column. Column is there in the User and I can access it through the Rails Console if I assign the user. User gets authenticated using devise right too. Here's my code in my Model;

MODEL

def self.something

    user = User.current
    if user.oauth.blank?

    else 

    end

end

I'm trying to think whats wrong and have no clue. I'm guessing I can pass that from the controller like so;

CONTROLLER

def index
   Model.something(current_user)
end

MODEL

def self.something(current_user)

   user = current_user
   if user.oauth.blank?

   end

end 

Haven't tested it, maybe it won't work that way either.

Upvotes: 1

Views: 1075

Answers (1)

Robin Daugherty
Robin Daugherty

Reputation: 7524

current_user is a controller helper and will not be available in the model. In fact, trying to use it within the model is a violation of the model-view-controller structure that Rails uses. While there may be hacks to allow this to work, I highly recommend finding an alternate solution to your problem.

For instance, if your model always expects current_user to contain the currently-logged-in user, what user should be used when Rails is running at the console? What about a rake task?

The correct method here is to pass current_user from the controller to the model, as you're doing in your code example, always. This means that any controller action that may end up needing to know the current user should have it included. In my projects I will always pass the current user within the context of the controller's action. An example:

class ThingsController
  def update
    @thing = Thing.find(params[:id])
    if @thing.update_attributes(thing_attributes_for_update)
      # Redirect with flash message
    else
      render :edit
    end
  end

  private

  def thing_attributes_for_update
    params[:thing].slice(%w(first_name last_name).merge({'updater' => current_user})
  end
end

Upvotes: 2

Related Questions