Ruby on rails 如何以一种干燥的方式创建此链接到条件?
我想做以下工作:Ruby on rails 如何以一种干燥的方式创建此链接到条件?,ruby-on-rails,ruby-on-rails-5,Ruby On Rails,Ruby On Rails 5,我想做以下工作: <% if current_user.has_role? :demo %> <%= link_to profile_path(@selected_profile) do %> <% else %> <%= link_to profile_path(profile) do %> <% end %> 您可以通过在user.rb(Model)中定义方法来实现这一点 然后你在你的视野中写作
<% if current_user.has_role? :demo %>
<%= link_to profile_path(@selected_profile) do %>
<% else %>
<%= link_to profile_path(profile) do %>
<% end %>
您可以通过在user.rb(Model)中定义方法来实现这一点 然后你在你的视野中写作
<% if current_user.demo? %>
<%= link_to profile_path(@selected_profile) %>
<% else %>
<%= link_to profile_path(profile) %>
<% end %>
这可能对你有帮助 您可以通过在user.rb(Model)中定义方法来实现这一点 然后你在你的视野中写作
<% if current_user.demo? %>
<%= link_to profile_path(@selected_profile) %>
<% else %>
<%= link_to profile_path(profile) %>
<% end %>
这可能对你有帮助
do
应该有end
选定的配置文件
轮廓
do
应该有end
选定的配置文件
轮廓
您可以这样做:
<% chosen_profile = current_user.has_role?(:demo) ? @selected_profile : profile %>
<%= link_to profile_path(chosen_profile) %>
因此,这将不会重复您需要执行的链接到标记。由于您必须重定向到同一路径,只需更改配置文件
对象,因此这将起作用。如果行看起来很长且不可读,则可以将三值块更改为if-else块
正如大家提到的,在需要块之前,不要在链接到之后使用do
。这样可以修复您的错误。您可以这样做:
<% chosen_profile = current_user.has_role?(:demo) ? @selected_profile : profile %>
<%= link_to profile_path(chosen_profile) %>
因此,这将不会重复您需要执行的链接到标记。由于您必须重定向到同一路径,只需更改配置文件
对象,因此这将起作用。如果行看起来很长且不可读,则可以将三值块更改为if-else块
正如大家提到的,在需要块之前,不要在链接到之后使用do
。因此,这将修复您的错误。由于do
,您正在打开块,但没有关闭它,请尝试此代码
<% if current_user.has_role? :demo %>
<%= link_to 'Profile', profile_path(@selected_profile) %>
<% else %>
<%= link_to 'Profile', profile_path(profile) %>
<% end %>
然后在视图中
<%= link_to 'Profile', profile_path(@selected_profile) %>
希望有帮助 由于do
,您正在打开块但未关闭,因此出现错误,请尝试此代码
<% if current_user.has_role? :demo %>
<%= link_to 'Profile', profile_path(@selected_profile) %>
<% else %>
<%= link_to 'Profile', profile_path(profile) %>
<% end %>
然后在视图中
<%= link_to 'Profile', profile_path(@selected_profile) %>
希望有帮助 不,你不理解这个问题。问题在于link\u to
中的do
和if
中的else
中的if
。您的建议将给我带来与现在相同的错误。从link\u to标记中删除do子句。我编辑了我的回答…兄弟…我需要它!接下来是if
块的全部内容。不,您不理解这个问题。问题在于link\u to
中的do
和if
中的else
中的if
。您的建议将给我带来与现在相同的错误。从link\u to标记中删除do子句。我编辑了我的回答…兄弟…我需要它!之后是if
块的全部内容。html代码在此
。。对于do
html代码,您需要end
。。对于do
你需要end
,是的,我试图不让代码重复…但我接受你的观点。是的,我试图不让代码重复…但我接受你的观点。@muistooshort抱歉,用括号括起来了。如果可能的话,如果有错误,请您更正。您自己刚刚发现。@muistooshort抱歉用括号括起来。如果可能的话,如果有错误,请你改正。你只是自己发现的。上面的部分不起作用,但下面的建议有点起作用。我仍然需要链接到
的中的do
。上面的部分不起作用,但下面的建议有点起作用。我仍然需要链接到
的链接中的do
。