我想查找一个很好的方法来检查我的对象,然后将它们显示在视图中,这样我就不会出错。Rails在显示之前检查对象是否存在
这是我CONTROLER
@user = User.find_by_username(params[:username])
@profile = @user.profile
@questions = @user.questions
,这是我的看法
<% unless @profile.blank? %><%= link_to 'Edit Profile', :controller => 'profiles', :action => 'edit' %><% end %>
<% unless @user.blank? %>
Username:<%= @user.username %><br />
Member Since:<%= @user.created_at.strftime("%d %B %Y") %><br />
<% end %>
<% unless @profile.blank? %>
First Name: <%= @profile.first_name %><br />
Last Name: <%= @profile.last_name %><br /><br />
About: <%= @profile.body %><br /><br />
Location: <%= @profile.location %><br />
Birthday: <%= @profile.birthday.strftime("%d %B %Y") %><br />
<% end %>
正如你所看到的,我使用的每种多于一个的检查(检查除非@ profile.blank ?),我认为会有更好的方式来做到这一点。
有没有Rails的方式来做比我想出的更聪明的事?
我只是不想显示用户信息(配置文件等),如果用户没有。一个空的配置文件将如何帮助我做到这一点? – Sharethefun 2010-09-26 15:01:32
好吧 - 创建没有配置文件的用户有什么意义? – Eimantas 2010-09-27 15:59:36
配置文件是另一种模式。并非每个人都有个人资料。 – Sharethefun 2010-09-30 04:29:46