Rails Checking if One Array is in Another

I have five models: Course, Lesson, Question, Answer and User.

What I'm trying to do is determine if the User has Answers for all of the Questions in a Lesson (so I can put "Done" next to the lesson in the view if this is the case).

My models:

class Course < ActiveRecord::Base
  has_many :lessons, dependent: :destroy
  has_many :questions, :through => :lessons
  has_many :users, through: :purchases

class Lesson < ActiveRecord::Base
  belongs_to :course
  has_many :questions, dependent: :destroy
  has_many :answers, through: :questions

class Question < ActiveRecord::Base
  belongs_to :lesson
  belongs_to :course
  has_many :answers, dependent: :destroy

class Answer < ActiveRecord::Base
  belongs_to :question
  belongs_to :user

class User < ActiveRecord::Base
  has_many :answers
  has_one :author
  has_many :courses, through: :purchases

What I tried to do was to check if a Lesson's Questions were in the Questions the User Answered, but the includes? line doesn't seem to be working the way I want.

in my controller, I have:

@lessons = @course.lessons
@answers = current_user.answers
@questions = Question.where(:id => @answers.map(&:question_id))

in my view, I have:

<% @lessons.each do |lesson| %>
  <% lesson_questions = lesson.questions %>
  <%= user_questions = @questions.where("lesson_id = ?", lesson.id)%>

  <% if user_questions.include?(lesson_questions)%>
  <% end %>
<% end %>

I'm not sure if this is the cause, but I noticed the lesson_questions are #<Question::ActiveRecord_Associations_CollectionProxy:0x9c49698>

While the user_questions are: #<Question::ActiveRecord_Relation:0x9c48330>

I'm wondering, (a) how I accomplish my objective of finding the Lessons with all of the Questions answered, and (b) if there's a more efficient way to do this. Thanks!



You can't check if an array includes another array just like this:


You need to check if each element from lesson_questions is included in the user_questions.

Try these instead:

Solution: 1
lesson_questions.all? { |lq| user_questions.include?(lq) }

This should return true if all the lesson_questions are included in the user_questions.

Solution: 2
(lesson_questions - user_questions).empty?

Need Your Help

Rspec/rails: How to test for sample(x) in a view

ruby-on-rails ruby rspec

I have a home page that is pulling random entries from my db using this code (probably not the best way, but it works)

Why does Java have virtual and not static extension methods like C#?

c# java extension-methods java-8

The Java language designer decided to use virtual extension methods instead of static extension methods like C#. Static extension methods can lead to naming conflicts with future methods, but inter...