2012-04-08 39 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