【问题标题】:How do I create this link_to conditional in a DRY way?如何以 DRY 方式创建此 link_to 条件?
【发布时间】:2016-12-12 05:43:19
【问题描述】:

我想做以下事情:

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

导致它失败的是link_to 中块的开头,在if 语句中。

那么,我如何在不重复此if 块中的所有代码两次的情况下实现这一点?

编辑 1

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

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

【问题讨论】:

  • &lt;%= link_to something do %&gt; html-code-here &lt;% end %&gt;.. 对于do,您需要end

标签: ruby-on-rails ruby-on-rails-5


【解决方案1】:

你可以这样做:

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

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

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

【讨论】:

  • @muistooshort 对不起,括号。如果可能的话,如果有错误,请纠正错误。
  • 你自己找到的。
【解决方案2】:

您可以通过在 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 %>

这可能会对您有所帮助。

【讨论】:

  • 不,你没有理解这个问题。问题在于link_to 中的doif 中的else
  • 你的建议会给我现在遇到的同样的错误。
  • 从 link_to 标记中删除 do 子句。我编辑了我的答案
  • 大声笑...兄弟...我需要它!接下来是if 块的全部内容。
【解决方案3】:

do 应该有end

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

【讨论】:

  • 是的,我试图避免重复代码……但我同意你的观点。
【解决方案4】:

由于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) %>

希望有帮助!

【讨论】:

  • 顶部不起作用,但底部的建议有点作用。我仍然需要link_to 中的do
猜你喜欢
  • 2012-04-10
  • 2012-04-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多