mercredi 2 décembre 2015

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
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!

Aucun commentaire:

Enregistrer un commentaire