Reputation: 1740
Guys I've a helper method in ApplicationController as follows
class ApplicationController < ActionController::Base
helper_method :current_user
end
And I want to call it in my model (say Project) as follows:
class Project < ActiveRecord::Base
after_save :update_other_tables
private
def update_other_tables
# if project saves, Create a new insteance into User Projects
@userproject=UserProject.new(
:user_id=>User.current_user.id,
:project_id=>self.id
)
@userproject.save
end
Here, I'm getting error like undefined method `current_user' So, How to call the this method in model? please help me
Upvotes: 0
Views: 592
Reputation: 2396
I would do it in the following way:
class ApplicationController < ActionController::Base
# Assignment method
def current_user=(user)
@current_user = user
end
# Returns the current user, nil otherwise
def current_user
@current_user
end
end
Now when a user logs in you can set:
current_user = the_user
And from the point onwards you can do:
current_user.id
Hope this helps.
Upvotes: 1
Reputation: 15579
not a ruby guy but I am guessing the User here isnt referring to the User that is present in your controller namespace and that is why there is no method current_user on the object.. You probably need to pass the User object to your helper method or just pass the id..
The above theory is from my experience dealing with something similar in .Net MVC so please correct me if I am wrong and I will delete the answer..
P.S: was too long of a comment
Upvotes: 0