marcamillion
marcamillion

Reputation: 33755

How do I create this link_to conditional in a DRY way?

I want to do the following:

<% if current_user.has_role? :demo %>   
 <%= link_to profile_path(@selected_profile) do %>    
<% else %>    
  <%= link_to profile_path(profile) do %>    
<% end %>

What's throwing it off is the beginning of the block in the link_to, within the if statement.

So how do I achieve this without having to duplicate ALL of the code within this if block twice?

Edit 1

This is the error I get from the above code:

SyntaxError at /
syntax error, unexpected keyword_else, expecting keyword_end
'.freeze;         else 
                      ^

Upvotes: 0

Views: 102

Answers (4)

Rajdeep Singh
Rajdeep Singh

Reputation: 17834

You are getting error because of do, you are opening the block but not closing it, try this code

<% if current_user.has_role? :demo %>   
 <%= link_to 'Profile', profile_path(@selected_profile) %>    
<% else %>    
  <%= link_to 'Profile', profile_path(profile) %>    
<% end %>

or, you can do it in controller instead

@selected_profile = current_user.has_role?(:demo) ? @selected_profile : profile

and then in the view,

<%= link_to 'Profile', profile_path(@selected_profile) %>

Hope that helps!

Upvotes: 0

Deepesh
Deepesh

Reputation: 6398

You can do it like this:

<% chosen_profile = current_user.has_role?(:demo) ? @selected_profile : profile %>
<%= link_to profile_path(chosen_profile) %>

So this will not repeat your link_to tag which you need to do. As you have to redirect to the same path and just change the profile object then this will work. You may change the ternary to if else block if the line seems very long and not readable.

And as everyone mentioned that don't use a do after link_to until you need a block. So that will fix your error.

Upvotes: 2

Srikanth Jeeva
Srikanth Jeeva

Reputation: 3011

do should have end.

  1. Here is the Ruby Doc reference for link_to
  2. Here is more about do in Ruby

    <% if current_user.has_role? :demo %>   
     <%= link_to profile_path(@selected_profile) do %> 
       selected profile
     <% end %>   
    <% else %>    
      <%= link_to profile_path(profile) do %> 
       profile  
      <% end %>  
    <% end %>
    

Upvotes: 0

Atul Shukla
Atul Shukla

Reputation: 171

You can achieve this by defining method in you user.rb (Model)

  def demo?
    self.has_role?("demo")
  end

Then you write in your view

<% if current_user.demo? %>   
 <%= link_to profile_path(@selected_profile) %>    
<% else %>    
  <%= link_to profile_path(profile)  %>    
<% end %>

This may help you.

Upvotes: 0

Related Questions