我在一个页面上有几个实例,我需要知道current_user是否有一个'tlk_with_me‘富文本附件。例如:
<%= current_user.tlk_with_me.present? ? 'update-class' : 'leave-class' %>
<%= f.submit "#{ current_user.tlk_with_me.present? ? 'Update' : 'Leave' } Your Details"... %>
<% if current_user.tlk_with_me.present? %>
<p class="create-remove-details">...</p>
<% end %>我对Rails的细节了解不多,但我想知道是这样做还是在视图(或控制器)中设置一个变量更有效。
例如:
<% current_user.tlk_with_me.present? ? @twm_present = true : @twm_present = false %>然后使用这个布尔值构建我的视图;例如:
<%= @twm_present ? 'update-class' : 'leave-class' %>如果能通过得到这个问题的答案来了解更多关于Rails的知识,那就太好了。谢谢。
发布于 2020-03-20 22:52:11
一种简单的方法是在用户模型中添加一个方法:
class User
def twm?
tlk_with_me.present?
end
end这样你就可以编写<%= current_user.twm? ? 'update-class' : 'leave-class' %>了
我不会担心多次调用它的效率,除非它是一个网络调用,然后你应该缓存它。
https://stackoverflow.com/questions/60776296
复制相似问题