1

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
end

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

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

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

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

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)%>
    Done!      
  <% 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!

1

1 Answer 1

2

Problem

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

user_questions.include?(lesson_questions)

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