2010-09-25 128 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 
相關問題