Rails:查询parents与孙辈(关联)

Rails: Query parents with grandchildren (associations)

class User < ActiveRecord::Base
  has_many :posts
end

class Question < ActiveRecord::Base
  belongs_to :user
  has_many :answers
end

class Answer < ActiveRecord::Base
  belongs_to :question
end

使用Rails 我怎样才能:

1.Return 所有 usersquestions?例如

@users_with_questions = User.joins(:question).where.not(question: { id: nil })

2.Return 所有 usersanswers?

试试这个:

children = Child.where( #something)
children_parents = Parent.joins(:children).where(children: {id: children} )

grandchildren = Grandchildren.where(#something)
grandchildren_parents = Parent.joins(children: :grandchildren).where(grandchildren: {id: grandchildren}) 

所以对于你的例子:

grandchildren_parents = Parent.joins(children: :grandchildren).where.not(grandchildren: {id: nil}).distinct

grandchildren_parents = Parent.includes(children: :grandchildren).where.not(grandchildren: {id: nil})

在ruby中:

@users_with_questions = User.all.select{|u| u.questions.present? }
@users_with_answers   = User.all.select{|u| u.questions.present? && u.answers.present? }

class User < ActiveRecord::Base
  has_many :questions
  has_many :answers, :through => :questions
end

在一个 sql 查询中(只是一种实现方式):

@users_with_questions = User.find(Question.pluck(:user_id).uniq!)
questions = Question.find(Answer.pluck(:question_id).uniq!)
@users_with_answers = User.find(questions.pluck(:user_id).uniq!)

1.Return 所有用户有问题?

@users_with_questions = User.includes(:question).where.not(:question => {id: nil})

2.Return 所有用户回答了吗?

@users_with_answers = User.includes(question: :answer).where.not(:answer => {id: nil})