Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails comparing values of params[:id] and session[:user_id] not working

I'm new to rails after moving from PHP and am having no end to the frustrations, but hopefully there is a steep learning curve.

I was following a guide on how to make a twitter clone in rails, and have continued along that path making it more and more twitter like.

So I've got a 'users' page /users/show.html.erb which show all the posts from a user.

Now, if the currently logged in user is the same as the page owner, I'm trying to show the text box so that the user can add a new entry.

I've got what should be a very simple

<% if params[:id] == session[:user_id] %>
    put the text box here
<% end %>

of course, that isn't working, but right above it I've output both the session[:user_id] and the params[:id], and the printout is exactly the same.

If I set the == to !=, I get the 'put the text box here' message.

any suggestions as to what I'm doing wrong? I know these two values match, as I can see in the url and the output of the currently logged-in user. I've also output

-<% session[:user_id] %>-
-<% params[:id] %>-

so that I can see there is no gaps or spaces or other characters on either end of the parameters, and it all looks clean.

The output looks like this

-4c4483ae15a7900fcc000003-
-4c4483ae15a7900fcc000003- 

which is the mongodb objectId of the user with dashes on either side to show that there are no spaces or anything.

like image 367
pedalpete Avatar asked Jul 19 '10 17:07

pedalpete


2 Answers

Are you sure that both items are simple strings? What happens if you run, say

params[:id].to_s == session[:user_id].to_s

?

like image 141
jasonpgignac Avatar answered Oct 22 '22 23:10

jasonpgignac


It could be like jasonpgignac pointed out. If you enter into IRB:

num = "7"
num2 = 7
num == num2 # => false

Make sure they are both of the same type. Putting <%= num2 %> will actually trigger the .to_s method... hence why the two appear to be equal when you output them in your .erb page.

Also, you might want to move that comparison into the controller. Something like:

@is_user_home = params[:id].to_s == session[:user_id].to_s

Then you can put in your view:

<% if @is_user_home %>
    code here
<% end %>

It makes the code a little more easier to read.

like image 44
Charles Caldwell Avatar answered Oct 22 '22 21:10

Charles Caldwell