Reputation: 483
How to write this sql
select * from interview_questions as iq inner join (select * from interview_answers as iaa where iaa.case_id=6 and iaa.used='t') as ia where iq.id = ia.interview_question_id;
with Ruby on Rails ActiveRecord? An interview_questions has many interview_answers, is a 1 to N relationship. I want to obtain the list of InterviewQuestion that this sql query would normally return.
Upvotes: 1
Views: 45
Reputation: 483
After the associations were done as suggested by @Gabriel Mesquita I needed this to complete my task.
InterviewQuestion.where(id: InterviewAnswer.where(case_id: params[:case_id], used: 't').pluck(:interview_question_id))
was the Ruby on Rails code that I looked for. It selects all interviews_questions that have an interview_answer corresponding to the current case_id and with the used set to 't'.
Upvotes: 1
Reputation: 2391
Assuming that you have a 1 to N relationship between your models you need to use The has_many Association like this:
http://guides.rubyonrails.org/association_basics.html#the-has-many-association
Rails guides explains:
A has_many association indicates a one-to-many connection with another model. You'll often find this association on the "other side" of a belongs_to association. This association indicates that each instance of the model has zero or more instances of another model. For example, in an application containing authors and books, the author model could be declared like this:
You probably gonna need to do this:
class interview_questions < ApplicationRecord
has_many :interview_answers
end
class interview_answers< ApplicationRecord
belongs_to :interview_questions
end
After that you need to create a migration to add foreing key in your interview_answers model.
rails generate migration add_interview_questions_to_interview_answers interview_questions:references
Finally you can use association helpers like
interview_questions.first.interview_answer.where(case_id: 6).where(used: 't')
Remember that this is just an example, you will probably need to adapt some minor things. Good luck!
Upvotes: 1