0

I am working on a reservation project and after login I want to pass the current user information from the Sessions Controller to a Reservations Controller via a home page. How can I do that? I have been following Michael Hartl's Rails Tutorial for the login. Here's what I have tried in the create section of the Sessions Controller

render home_path :local_variables[:id => user_id]

and in the home_path(users#home)

<%= link_to new_reservation_path(:user_id => :id) %>

but it shows me an undefined method error. My Reservation model has a user_id column.I am confused regarding this matter. What should I do?

1 Answer 1

1
render home_path :local_variables[:id => user_id]

Seems weird to me to pass locals that way (don't even know if it's possible, never seen locals used outside of rendering views/partials).

I think the best way is to redirect instead and set the user in the sessions once they have been logged in successfully, so in your login action:

user = User.find_by_email(params[:user][:email]) # or however you are finding the person trying to login

session[:user] = user
redirect_to home_path

then in users#home

@user = session[:user]

and finally, in the view:

<%= link_to new_reservation_path(:user_id => @user.id) %>

EDIT

Actually, probably not a good idea to store an object in the session, instead of

 session[:user] = user

You could try:

 session[:user_id] = user.id

and then to find the user:

@user = User.find(session[:user_id])

If you still get an undefined error then it's probably because the user is nil (unless the User model actually has no id attribute, which would be strange) so there might be an issue with the login part, it's hard to say without knowing what that looks like.

If you need the logged in user on every page, you could abstract the functionality out into the application controller:

before_filter :check_user

def check_user
  @user = User.find(session[:user_id]) if session[:user_id]
end

Then, you can use the @user instance variable anywhere in your app.

Sign up to request clarification or add additional context in comments.

2 Comments

It's still not working. Shows undefined method 'id' error
Thanks for the solution @martincarlin87, I did it by the first method in your edit and now I can use the user information in my other controller

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.