Reputation:
how would i write this SQL query in ruby:
Select Id,Name,Email,number
from Participants
INNER JOIN Winners
on Winner.participant_id = Participant.id && Winner.sweepstake_id = Participant.sweepstake_id
Participants and Winners have one to one relationship.
P.S : I don`t know whether this query is correct or not but hope you get the idea what i am trying to achive.
Upvotes: 2
Views: 239
Reputation:
This solved my problem:
Participant.joins(:winner).where(:sweepstake_id => params[:id]
)
Upvotes: 0
Reputation: 2747
Try this:
Participant.joins("INNER JOIN Winner ON Winner.id = Participant.id AND Winner.sweepstake_id = Participant.sweepstake_id").select("participants.id, participants.name, participants.email, participants.number")
Upvotes: 1
Reputation: 3803
Participant.joins("inner join winners on winners.id = participants.id AND winners.sweepstake_id = participants.sweepstake_id ").select("participants.id, participants.name,participants.email,participants.number")
Try this
Upvotes: 1
Reputation: 3842
The convention for Rails is to have tables named participants
and winners
(for models Participant
and Winner
), and to also lowercase the column names. Its also strange to join onto two primary keys: one of those should be a foreign key. In any case, if we assume those naming changes, but keeping the join conditions the same, you can query this in ActiveRecord like so:
@participants = Participant.select(:id, :name, :email, :number)
.joins("INNER JOIN winners ON winners.id = participants.id AND winners.sweepstakes_id = participants.sweepstakes_id")
Upvotes: 0