0

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...
2
  • 1
    What code are you using to get the collection of models? Commented Apr 8, 2012 at 20:41
  • I just added the area thats breaking Commented Apr 8, 2012 at 20:44

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.