简体   繁体   中英

Rails query with inner join

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.

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!

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'.

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