0

I have a method that looks for random answers and puts them into an array:

def self.answer_list(user)
  answers = Array.new
  for i in 1..25
    answer = random(user)
    if !answer.nil? && !answers.include?(answer)
      answers << answer 
    end
  end
  return answers
end

the include? method is suposed to not let the record go into the array if it is already there, but it puts it in anyway

How do I compare the new record to make sure something similar is not already inside the array? the record returned from the random method is something like this

 return answer = Answer.new(user_id: user.id, contact_id: contact.id, statement_id: statement.id)

2 Answers 2

1

Two ActiveRecord models are equals if they are not new_record and if they have the same ID. http://apidock.com/rails/ActiveRecord/Base/%3D%3D

Here, the equivalence can not be set because your two objects are new records.

You have 2 solutions :

  • define an ==(val) function in your Answer model
  • do something like that :

    if !answer.nil? && answers.detect{|a| a.user_id == user.id}.nil?
       ...
    end
    
Sign up to request clarification or add additional context in comments.

Comments

1

This doesn't really answer the question, but if you want a random N elements from an array, you can just use sample:

user.answers.sample(n)

Assuming your user has_many :answers. I don't see anything that is obviously wrong with your code, include? should work as expected here I believe.

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.