Active Record Query to select an entry, that does not already have a vote that I have already given

59 Views Asked by At

I have the following three models

Judge (Devise User)

Judge.column_names
=> ["id", "email", "encrypted_password", "reset_password_token", "reset_password_sent_at", "remember_created_at", "sign_in_count", "current_sign_in_at", "last_sign_in_at", "current_sign_in_ip", "last_sign_in_ip", "created_at", "updated_at", "confirmation_token", "confirmed_at", "confirmation_sent_at", "unconfirmed_email"]

class Judge < ActiveRecord::Base
   has_many :votes
end

Entry

Entry.column_names
 => ["id", "entrant_id", "title_of_work", "price", "created_at", "updated_at", "media_file_name", "media_content_type", "media_file_size", "media_updated_at", "paid", "height", "width", "type_of_media"]

class Entry < ActiveRecord::Base
    belongs_to :entrant
    has_many :votes
end

Vote

Vote.column_names
=> ["id", "entry_id", "judge_id", "score", "created_at", "updated_at"]

class Vote < ActiveRecord::Base
    belongs_to :entry
    belongs_to :judge
end

I need a query that does the following

If I'm logged in as a judge, select one paid for entry, that does not already have a vote that I have already given.

I have this but it doesn't seem to work

Entry.where(:paid => 1).includes(:votes).where.not(votes: { id: nil }).where.not(votes: {judge_id: current_judge.id }).first

I'm trying to create a page that shows an 'entry' which can be voted on. Once the vote is given there will be a record in the Votes table and it will never be shown again. There are many judges so each of these rules applies to each judge.

Is there a better way of doing this?

2

There are 2 best solutions below

0
On BEST ANSWER

This may solve your problem

Entry.includes(:votes).where(paid: 1).where("votes.judge_id != ? ", current_judge.id)
0
On

If you mean to say that you are judge and want to fetch entry which is paid and does not have any votes given by you? Then following query might help you: Entry.includes(:vote).where('paid = 1 and votes.judge_id <> ?', current_judge.id).references(:votes)