Chris Hawkins
Chris Hawkins

Reputation: 658

Arrays in Rails

After much googling and console testing I need some help with arrays in rails. In a method I do a search in the db for all rows matching a certain requirement and put them in a variable. Next I want to call each on that array and loop through it. My problem is that sometimes only one row is matched in the initial search and .each causes a nomethoderror.

I called class on both situations, where there are multiple rows and only one row. When there are multiple rows the variable I dump them into is of the class array. If there is only one row, it is the class of the model.

How can I have an each loop that won't break when there's only one instance of an object in my search? I could hack something together with lots of conditional code, but I feel like I'm not seeing something really simple here.

Thanks!

Requested Code Below

@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...

Upvotes: 0

Views: 471

Answers (1)

Chris Cherry
Chris Cherry

Reputation: 28554

Use find_all_by_email, it will always return an array, even empty.

@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

Upvotes: 2

Related Questions