仅显示轨道ERB中是否存在记录的优雅方式 [英] Elegant way to only show records if they exist in rails ERB
本文介绍了仅显示轨道ERB中是否存在记录的优雅方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我发现在显示有关用户的信息时,我在ERB视图中使用了很多重复代码。
I'm finding that I'm using a lot of repetitive code in my ERB views when displaying information about a user. Along the lines of
<% if @user.name.present? %>
<%= @user.name %>
<% end %>
我基本上是为了避免错误(例如,可能不会拥有所有新字段)。
I'm basically doing this for everything in my view to avoid errors (e.g. older users who may not have all the new fields).
有没有更好的方法?
推荐答案
将逻辑移至帮助器中:
def name_for(user)
user.name if user.name.present?
end
然后在您的视图中调用该帮助程序:
And call that helper in your views :
<%= name_for(@user) %>
这篇关于仅显示轨道ERB中是否存在记录的优雅方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文