Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Wrong query given when using negative predictes #1117

Open
Doctor06 opened this issue Apr 21, 2020 · 1 comment
Open

Wrong query given when using negative predictes #1117

Doctor06 opened this issue Apr 21, 2020 · 1 comment

Comments

@Doctor06
Copy link

Ruby 2.5
Rails 5.2.4.1
Ransack 2.3.2

I have a user model that has many projects.
Project has a relationship with tags that is a habtm.
Here are my simplified classes.

class User < ApplicationRecord
  has_many :projects
end
class Project < ApplicationRecord
  belongs_to :user
  has_and_belongs_to_many :tags
end
class Tag < ApplicationRecord
  has_and_belongs_to_many :projects
end

When i try to do a search on a project and do a not_in for tags_id I get the correct query output.
Project.ransack(tags_id_not_in: [1,2]).result.to_sql

SELECT projects.* 
FROM projects 
WHERE projects.id NOT IN 
  (SELECT projects_tags.project_id 
  FROM projects_tags 
  INNER JOIN tags ON tags.id = projects_tags.tag_id 
  WHERE projects_tags.project_id = projects.id 
  AND NOT (tags.id NOT IN (1, 2)))

if i try to get the projects tags id where not in, through the User model, then i start getting the incorrect query.

User.ransack(projects_tags_id_not_in: [1,2]).result.to_sql

SELECT users.* 
FROM users 
LEFT OUTER JOIN projects ON projects.user_id = users.id 
WHERE users.id NOT IN 
  (SELECT projects_tags.project_id 
  FROM projects_tags 
  INNER JOIN tags ON tags.id = projects_tags.tag_id 
  WHERE projects_tags.project_id = users.id 
  AND NOT (tags.id NOT IN (1, 2)))

You can see the second query's subquery is selecting projects_tags.project_id and comparing it with users.id.
It is also doing this in the subquery WHERE projects_tags.project_id = users.id

I would think the query should be:

SELECT users.* 
FROM users 
LEFT OUTER JOIN projects ON projects.user_id = users.id 
WHERE projects.id NOT IN 
  (SELECT projects_tags.project_id 
  FROM projects_tags 
  INNER JOIN tags ON tags.id = projects_tags.tag_id 
  WHERE projects_tags.project_id = projects.id 
  AND NOT (tags.id NOT IN (1, 2)))

I hope this was a detailed enough issue, If not, please let me know how i can give more information.

Here is the Gist

@Doctor06
Copy link
Author

Tried fixing this issue and created a pull request. Let me know if there is anything you see wrong with it.
#1123

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant