显示用户可能没有的数据的最佳实践
我有一个 Ruby on Rails 应用程序,我在其中执行以下操作
@user = User.find(:first, :conditions => ['LOWER(username) = ?', current_subdomain.downcase], :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
有什么解决方案可以显示用户获得的数据吗?
提前致谢!
更新
好吧,如果弄清楚了一些事情:
<% 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 %>
但它似乎有点矫枉过正?还有更好的建议吗?
谢谢!
I've got a Ruby on Rails app where I do the following:
@user = User.find(:first, :conditions => ['LOWER(username) = ?', current_subdomain.downcase], :include => :bio)
Where ':include => :bio' is the important part.
Then in the view I want to display some bio:
<em><%= @user.bio.title %></em><br />
<%= @user.bio.city %><br />
<%= @user.bio.state %><br />
<%= @user.bio.country %>
But if the user dosn't have any information it just will turn up a couple of blank rows.
I've tried a couple of different things, none has worked so far...
<% 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
Any sollution to how to just display the data the user has got?
Thanks in advance!
UPDATE
Ok, if figured some things out:
<% if @user.bio.title %> # Works if the bio isn't set at all.
<% if @user.bio.title > 0 %> # Works if the bio is set.
So I can use a sollution that looks like:
<% if @user.bio.title %><% if @user.bio.title > '0' %><%= @user.bio.title %><% end %><% end %>
But it seam a little overkill? Any better suggestions?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是一种思考方式。 用户有一个个人简介,并已填写标题字段。在 Ruby 中:
如果您要显示个人简介中的多个字段,您可以将其分为 2 个检查,例如
Alternative
另一种方法是在模型上添加方法以提供对生物字段的直接访问。例如
,那么在你看来你可以这样做:
Here's one way to think about it. The user has a bio and has filled in the title field. In Ruby:
If you are going to display multiple fields from the bio you can separate this into 2 checks e.g.
Alternative
Another way is to put methods on your model to provide direct access to the bio fields. e.g.
Then in your view you can just do:
你能试试这个吗?
Can you try this?
也许您可以查看 object .try 还是 andand?
Maybe you can check out object.try or andand?