0

I needed to access the current_user in my another model. I googled and found a few solutions and tried this.

But just one difference: I didn't set the User.current_user in the controller. WHY?

Like in the answer I followed I'm not adding data to my second model from views but by rendering data via a url (with open-uri, it's csv data I'm fetching).
So in my second model I do:

Person.create(username: User.current_user.username)  

It gives:

NoMethodError: undefined method `username' for nil:NilClass

which isn't working (which is obvious I guess). In console when I do User.current_user it shows:

1.9.3p448 :002 > User.current_user
=> nil

I think why it isn't working is because I'm accessing the User.current_user directly from model and model cannot get the current_user unless it is given that. (right?)

But this would definitely work if I access it via a login page and set the User.current_user in the controller.

But as I'm directly fetching the data from url, I'm directly making new entries for my Person model in model itself.

So how do I set the User.current_user?

Is there any workaround for this? Edit's for the question's title are required.

4

1 回答 1

1

current_user is available by default as a helper method within Devise. From the documentation:

# For the current signed-in user, this helper is available:
current_user

The current_user isn't accessed directly via the model, per se, but rather, though the Devise module, which looks up the User object that is logged into the current session, and then returns to current_user.

Thus, the current user isn't accessed via User.current_user (there is no current_user method on User, as the error message is saying). You access it purely by invoking the current_user helper method within a controller or view.

UPDATE:

You're well advised to keep your controller and model layers separate. One way of doing what you've proposed is to create a class function on the Person model wherein you explicitly pass the username of your User object from within your controller:

# in your controller
Person.create_with_username(:username => current_user.username)

# app/models/person.rb
def self.create_with_username(username)
    self.create(username)
end
于 2013-09-01T21:02:13.707 回答