Andrew K
Andrew K

Reputation: 1599

Rails 4 - How to query a has_many model to find objects based on associations

I am running Rails 4 on Heroku using Devise gem.

I have two models in question: posts and votes. I am trying to find all posts that a user has not yet voted on. I cannot figure out the proper way to use rails ActiveRecord to make this query. So far, I have tried:

@posts = Post.includes(:votes).where('votes.user_id != ?', current_user.id)

and I have tried:

@posts = Post.joins(:votes).where.not( votes: {user_id: current_user.id})

which did not fetch any results.

In the model, I have the Has_many relationship set up as:

class Post < ActiveRecord::Base
  belongs_to :user
  has_many :images, dependent: :destroy
  has_many :votes, dependent: :destroy
end

This is probably an easy question for someone who is more experienced to answer, but I have tried searching through RailsGuides Active Record Query Interface to no avail.

Upvotes: 1

Views: 3842

Answers (1)

Kirti Thorat
Kirti Thorat

Reputation: 53018

Use

@posts = Post.includes(:votes).where('votes.user_id <> ? or votes.user_id is null', current_user.id)

I suppose that your query is not retrieving the 3 records as votes.user_id is null for them.

Upvotes: 5

Related Questions