显示用户可能没有的数据的最佳实践

时间:2010-08-04 11:45:06

标签: ruby-on-rails ruby erb

我有一个Ruby on Rails应用程序,我在其中执行以下操作:

@user = User.find(:first, :conditions => ['LOWER(username) = ?', current_subdomain.downcase], :include => :bio)

其中':include => :生物'是重要的一部分。

然后在视图中我想显示一些生物:

<em><%= @user.bio.title %></em><br />
<%= @user.bio.city %><br />
<%= @user.bio.state %><br />
<%= @user.bio.country %>

但如果用户没有任何信息,那么它就会出现几行空白。

我尝试了几件不同的事情,到目前为止还没有工作......

<% if @user.bio.title %> # is always true
<% if @user.bio.title > 0 %> # triggers an error if @user.bio.title isn't set
<% unless @user.bio.title.empty? %> # same as above

如何只显示用户获得的数据?

提前致谢!

更新

好的,如果弄清楚了一些事情:

<% if @user.bio.title %> # Works if the bio isn't set at all.
<% if @user.bio.title > 0 %> # Works if the bio is set.

所以我可以使用看起来像的溶剂:

<% if @user.bio.title %><% if @user.bio.title > '0' %><%= @user.bio.title %><% end %><% end %>
但它接缝有点矫枉过正?还有更好的建议吗?

谢谢!

3 个答案:

答案 0 :(得分:3)

这是考虑它的一种方式。 用户有一个生物,并填写了标题字段。在Ruby中:

<% if @user.bio && !@user.bio.blank? %> 

如果要显示bio中的多个字段,可以将其分为2个检查,例如

<% if @user.bio %>
  <% unless @user.bio.title.blank? %>
    Title: <%= @user.bio.title %>
  <% end %>
  <% unless @user.bio.other_field.blank? %>
    Other field: <%= @user.bio.other_field %>
  <% end %>
<% end %>

<强>替代

另一种方法是在模型上放置方法以提供对生物领域的直接访问。 e.g。

# return the user's title or nil if no bio
def title
  bio.title if bio
end

然后在你看来你可以这样做:

<% unless @user.title.blank? %>
  Title: <%= @user.title %>
<% end %>

答案 1 :(得分:0)

你能试试吗?

if defined?(@user.bio.title)

答案 2 :(得分:0)

也许您可以查看object.tryandand