我有一个Ruby on Rails应用程序,其中执行以下操作:
@user = User.find(:first, :conditions => ['LOWER(username) = ?', current_subdomain.downcase], :include => :bio)
其中':include =>:bio'是重要的部分。
然后在视图中,我想显示一些生物:
<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
如何仅显示用户获得的数据有什么解决方法?
提前致谢!
UPDATE
好吧,如果发现了一些问题:
<% 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 %>
但这缝了一点矫over过正? 还有更好的建议吗?
谢谢!
这是一种思考方式。 用户具有简历,并已填写标题字段。 在Ruby中:
<% if @user.bio && [email protected]? %>
如果要显示简历中的多个字段,可以将其分为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 %>
替代
另一种方法是在模型上放置方法以提供对生物领域的直接访问。 例如
# 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 %>
你可以试试这个吗?
if defined?(@user.bio.title)
也许你可以检查出object.try或andand ?