Ruby on rails 显示用户可能没有的数据的最佳做法
我有一个Ruby on Rails应用程序,可以执行以下操作:Ruby on rails 显示用户可能没有的数据的最佳做法,ruby-on-rails,ruby,erb,Ruby On Rails,Ruby,Erb,我有一个Ruby on Rails应用程序,可以执行以下操作: @user = User.find(:first, :conditions => ['LOWER(username) = ?', current_subdomain.downcase], :include => :bio) 其中“:include=>:bio”是重要的部分 然后在视图中,我想显示一些bio: <em><%= @user.bio.title %></em><br
@user = User.find(:first, :conditions => ['LOWER(username) = ?', current_subdomain.downcase], :include => :bio)
其中“:include=>:bio”是重要的部分
然后在视图中,我想显示一些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
#总是正确的
如果未设置@user.bio.title,则0%>#会触发错误
#同上
如何只显示用户获得的数据,有什么解决方案吗
提前谢谢
更新
好吧,如果你想好了一些事情:
<% if @user.bio.title %> # Works if the bio isn't set at all.
<% if @user.bio.title > 0 %> # Works if the bio is set.
如果bio根本没有设置,#就可以工作。
如果设置了bio,则0%>#有效。
所以我可以使用一种溶液,它看起来像:
<% if @user.bio.title %><% if @user.bio.title > '0' %><%= @user.bio.title %><% end %><% end %>
“0%”
但这有点过分了?还有更好的建议吗
谢谢 你能试试这个吗
if defined?(@user.bio.title)
这里有一种思考的方式。用户有个人简历,并填写了标题字段。在Ruby中:
<% if @user.bio && !@user.bio.blank? %>
在你看来,你可以做:
<% unless @user.title.blank? %>
Title: <%= @user.title %>
<% end %>
标题:
也许您可以退房,或者 当我现在快速尝试时,Seams总是返回false:我喜欢这里的替代方法,将视图代码拉到模型代码中。
# 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 %>