如何以 DRY 方式创建此 link_to 条件?

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

我想执行以下操作:

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

if 语句中 link_to 块的开头。

那么我如何实现这一点而不必将此 if 块中的所有代码复制两次?

编辑 1

这是我从上面的代码中得到的错误:

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

您可以通过在 user.rb (Model) 中定义方法来实现此目的

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

那你写在你的观点里

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

这可能对您有所帮助。

do 应该有 end

  1. 这是 link_to
  2. Ruby Doc 参考
  3. 这里有更多关于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 %>
    

你可以这样做:

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

所以这不会重复您需要做的 link_to 标签。因为您必须重定向到相同的路径并且只需更改 profile 对象,那么这将起作用。如果该行看起来很长且不可读,您可以将三元组更改为 if else 块。

并且正如每个人提到的那样,在需要块之前不要在 link_to 之后使用 do。这样就可以解决您的错误。

由于 do,您遇到了错误,您正在打开块但没有关闭它,请尝试此代码

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

,您可以改为在控制器中进行

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

然后在视图中,

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

希望对您有所帮助!