2016-09-08 2 views
2
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 все users с questions? например.

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

2.Return все users с answers?

+0

все родители с детьми, например? [jack, john, steven] возвращает [jack_parrent, john_parent, steeven_parent]. это то, что вы хотите? –

+0

в рубине? или с одним запросом sql? –

+0

непонятно, что вы спрашиваете –

ответ

0

попробовать это:

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}) 
+0

Это возвращает родительскую запись для каждого grandchilren, в результате чего дубликаты –

+0

я отредактировал, попробуйте то же самое с методом 'distinct' –

+0

Метод' includes' достигнет этого без необходимости 'distinct' –

0

В рубина:

@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!) 
0

1.Return всех пользователей с вопросами?

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

2.Отменить все пользователи с ответами?

@users_with_answers = User.includes(question: :answer).where.not(:answer => {id: nil}) 
Смежные вопросы