2010-09-25 129 views
3

我想查找一个很好的方法来检查我的对象,然后将它们显示在视图中,这样我就不会出错。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的方式来做比我想出的更聪明的事?

回答

5

正如我所看到的,您无法跳过此@ .blank?验证你不想要显示的记录,如果它们是空的,但我有几个建议

1 - 让下面的章节为谐音

<% 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 %> 

它会保持你的看法更清洁并会给你在你的应用程序中使用它们的灵活性

2 - 采取以下行

<% unless @profile.blank? %><%= link_to 'Edit Profile', :controller => 'profiles', :action=> 'edit' %><% end %> 

轮廓显示为更合适的

欢呼

sameera

0

如何在保存之前为用户构建空白配置文件?如何使用类似的感叹号,将提高ActiveRecord::RecordNotFound哪些反过来将显示404页。

P.S.我还建议将修剪控制器降至一个实例变量。

+0

我只是不想显示用户信息(配置文件等),如果用户没有。一个空的配置文件将如何帮助我做到这一点? – Sharethefun 2010-09-26 15:01:32

+0

好吧 - 创建没有配置文件的用户有什么意义? – Eimantas 2010-09-27 15:59:36

+0

配置文件是另一种模式。并非每个人都有个人资料。 – Sharethefun 2010-09-30 04:29:46

9

也在里面

<%= if @object.present? %> 

找我比

<%= unless @object.blank? %> 
多少simplier

特别是当我们有多个条件语句时(&& \ || \ and \ or)。

api.rubyonrails.org

0

根据轨道的文档,你可以看到,如果使用association.nil存在任何关联的对象?方法:

if @book.author.nil? 
    @msg = "No author found for this book" 
end 
相关问题