简体   繁体   中英

How i can do one switch with link by role, ruby on rails

I 'm new to ROR . I'm trying to make a switch with conditions. Someone can help me with the correct code

<%= link_to "Profile", (user = User.find(1)
case user.role
when "A"
redirect_to(url)
when "B"
redirect_to(url)
when "C"
redirect_to(url)
else
redirect_to(url)
end)%></i>

Try with below code.

<% user = User.find(1) %>
<% case user.role %>
<% when "A" %>
  <%= link_to "Profile", "YOUR URL" %>
<% when "B" %>
  <%= link_to "Profile", "YOUR URL" %>
<% when "C" %>
  <%= link_to "Profile", "YOUR URL" %>
<% else %>
  <%= link_to "Profile", "YOUR URL" %>
<% end %>

One, more thing it's not good to write this code into view file. rails provide helper method to write your business logic for view file.

In user helper

 def role_link(user)
  case user.role
    when 'A'
      url = 'redirect_url'
    when 'B'
      url = 'redirect_url'
    when 'C' 
      url = 'redirect_url'
  else
    url = 'redirect_url'
  end
  url
end

In view file

  <%= link_to 'profile', role_link(User.find(1) %>

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