I am having a terrible time understanding the assignment function that is needed, as explained in chapter 8.2.3. of the Hartl’s tutorial.
As context, he is focused on the second line of the following sign_in function:
def sign_in(user)
cookies.permanent[:remember_token] = user.remember_token
self.current_user = user #<-- this line
end
Where he mentions because its an assignment, it must be then separately defined as
def current_user=(user)
@current_user = user
end
Where the method current_user= expressly designed to handle assignment to current_user. My confusions is:
-
Why is this even necessary? I thought that a simple
=would allow you to assign things. For exampleuser.email = hello@kitty.com -
Also, when eventually he will code
redirect_to current_user, how does something that belongs to theSessionsControllerget translated to a view controlled byUsersController?
Thanks!!
The reason being it is needed as to avoid confusion (for the interpreter/VM) between method invocation and variable assignment
What’s happening there is that he is doing two things, firstly invoking the
current_user=method with the user object and secondly, setting that to@current_user(it’s not a great example – you’d probably end up doing a lot more in real life if you were to make acurrent_user=method such as setting up session variables).secondly
redirect_to current_useris equivalent toredirect_to user_path(current_user)– check out http://api.rubyonrails.org/classes/ActionController/Redirecting.html for more details which explains the different parameter kinds that redirect_to can take. Note this is a redirect, not a render – so a second HTTP request happens here.