2012-04-08 38 views
0

經過大量的搜索和控制檯測試之後,我需要一些幫助。在一個方法中,我在數據庫中搜索符合特定要求的所有行,並將它們放入一個變量中。接下來,我想調用每個數組並循環遍歷它。我的問題是,在初始搜索中有時只有一行匹配,每個.each導致一個nomethoderror。Rails中的陣列

我在兩種情況下都調用了類,其中有多行且只有一行。當有多行時,我將它們轉儲到的變量是類數組。如果只有一行,那就是模型的類。

當我的搜索中只有一個對象實例時,我怎樣才能讓每個循環都不會中斷?我可以用很多條件代碼一起破解一些東西,但是我覺得我在這裏看不到一些非常簡單的東西。

謝謝!

請求的代碼下面

@user = User.new(params[:user]) 
if @user.save  
    #scan the invites dbtable and if user email is present, add the new uid to the table 
    @talentInvites = TalentInvitation.find_by_email(@user.email) 
    unless @talentInvites.nil? 
     @talentInvites.each do |tiv| 
     tiv.update_attribute(:user_id, @user.id) 
     end 
    end 
....more code... 
+1

您使用什麼代碼來獲取模型集合? – ctcherry 2012-04-08 20:41:30

+0

我剛剛添加了區域,打破 – 2012-04-08 20:44:49

回答

2

使用find_all_by_email,它總是會返回一個數組,甚至是空的。

@user = User.new(params[:user]) 
if @user.save  
    #scan the invites dbtable and if user email is present, add the new uid to the table 
    @talentInvites = TalentInvitation.find_all_by_email(@user.email) 
    unless @talentInvites.empty? 
     @talentInvites.each do |tiv| 
     tiv.update_attribute(:user_id, @user.id) 
     end 
    end 
+0

謝謝你做的伎倆! – 2012-04-08 20:50:20