简体   繁体   中英

Ruby on Rails If…Else

I have the following code:

<div class="category_name">
     <%= current_user %>
     <%= review.user.front_name %>
      <% if current_user.name = review.user.front_name %>
      <%= link_to "You", user_path(review.user) %> / <%= review.categories_list %>
      <% else %>
      <%= link_to review.user.front_name, user_path(review.user) %> / <%= review.categories_list %>
      <% end %>
    </div>

It renders something like:

Tom Murphy Bill Smith You / Films

Why is this happening?

<% if current_user.name = review.user.front_name %>

In other words, if Tom Murphy = Bill Smith...which it doesn't...shouldn't it go to the line AFTER the 'else'? That's what I want to happen.

replace <% if current_user.name = review.user.front_name %> with

<% if current_user.name == review.user.front_name %>

you put = , you have to put ==

In Ruby to check equality you should use double equal signs ( == ).

Also - Currently you are comparing the names. You should compare the objects (User) to avoid mistakes or even worse (security breaches).

<% if current_user == review.user %>

Just modify: <% if current_user.name = review.user.front_name %> to

<% if current_user.name == review.user.front_name %>

The == ( double equal) Test for equal value..

when you want to make conditional statement. you should compare your statement. for example:

if number == 10
   print "Variable is 10"
elsif number == "20"
   print "Variable is 20"
else
   print "Variable is something else"
end

on your case please change the line:

<% if current_user.name = review.user.front_name %>

change intoenter code here

<% if current_user.name == review.user.front_name %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM