I am trying to make sure that the following method
def current_user
current_user = current_member
end
Is available to all actions in all my controllers I have tried putting it in the ApplicationsController with no luck.
I tried using solutions in the following
Where to put Ruby helper methods for Rails controllers?
With no effect.
What is the Rails-way solution to this?
I have the same method in my ApplicationsHelper and I can access it in my views no problem.
EDIT:
To give more detail. I had an application with an authentication system I built from scratch and this used a function in a SessionHelper file called "current_user"
I have been implementing Devise into my app, and maintained my user model to hold the user details, but created a member model to hold the devise authentication information (i.e. keep the user profile info separate from the table devise is using as suggested by the doc).
This gives me a devise helper method called current_member (based on my naming of the model).
I have "current_user" all over my app, both in controller actions and in views.
I want to create an app-wide helper that will alias current_member to current_user. Strictly speaking in my question my function is wrong - this will assign current_user to an instance of the member class. Since there is a one to one relationship between member and user, with the foreign key being member.id the correct function is....
def current_user if member_signed_in? current_user = User.find_by_member_id(current_member.id) end end
My ApplicationHelper:
module ApplicationHelper
def current_user
if member_signed_in?
current_user = User.find_by_member_id(current_member.id)
end
end
end
This takes care of current_user in all the views, But I can't get it to work in the controllers...see for example this code in my "show" action of the UserController
def show
@associates = []
@colleagues = current_user.nearbys(1000).take(20)
@colleagues.each do |associate|
unless current_user.following?(associate) || current_user == associate
@associates.push(associate)
end
end
impressionist(@user)
end
Forget the logic- I am just using geocoder to find nearly users. Its that current_user is resolving to "nil".
Even if I put
before_action :current_user
def current_user
if member_signed_in?
current_user = User.find_by_member_id(current_member.id)
end
end
In the UserController, current_user isn't working within the action. I have current_user in actions of other controllers too and the app breaks at these points, but not when current_user is in a view.
Let me know if you need more info.
EDIT 2:
I added
before_action :authenticate_member!
To the UsersController, but this still had no effect.
EDIT 3:
I'm an idiot. The nil class error was occurring because I had no seed data in the database, thus the
@colleagues = current_user.nearbys(1000).take(20)
@colleagues was nil, and therefore calling "take" on nil was throwing an error. Rookie mistake.