[英]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.