繁体   English   中英

如何在控制器中创建一个方法,以便在轨道上的ruby视图中调用IF条件?

[英]How to create a method in controller for the IF condition to call in the view in ruby on rails?

我是新手。 我只想在控制器中为以下代码创建一个方法,以避免在视图中再次重复。 如何在轨道上的红宝石中以简短而优雅的方式书写?

<% @A = ....... %>
<% @B = ....... %>
<% @C = ....... %>
<% @D = ....... %>
<% @E = ....... %>

<% if (@A || @B || @C) %>
  <label> One: </label>
  <%= ... %>

  <label> Two: </label>
  <%= ... %>
<% end %>

<% if (@A || @B || @C || (@D && @E)) %>
  <label> Three: </label>
  <%= ... %>
<% end %>

假设您的模型名为User ,您提供的代码放在“app / views / users / show.html.erb”中

我建议进行以下重构:
(您需要使用适当的逻辑替换A,B,C,D and E ,并将方法重命名为更有意义的方法)

# in "app/helpers/users_helper.rb"
module UsersHelper
  def isABC
    return A || B || C
  end

  def isDandE
    return D && E
  end
end

# in "app/views/users/show.html.erb
<% if (isABC) %>
  <label> One: </label>
  <%= ... %>

  <label> Two: </label>
  <%= ... %>
<% end %>

<% if (isABC || isDandE) %>
  <label> Three: </label>
  <%= ... %>
<% end %>

你可以在这里阅读Rails助手: http//paulsturgess.co.uk/articles/49-using-helper-methods-in-ruby-on-rails

基本上,控制器的可重用性是接受传入的Web请求,获取必要的数据( Model )并调用适当的View进行渲染。

Rails有可以从你的Views调用的Helpers 习惯用法是将视图中使用的任何高级逻辑放入Helper

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM