简体   繁体   中英

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!

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM