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

Polymorphic association in model with query constraints pointing to incorrect records #50315

Closed
iamradioactive opened this issue Dec 9, 2023 · 1 comment · Fixed by #50321

Comments

@iamradioactive
Copy link
Contributor

Steps to reproduce

While working on #50297 I found another bug related to query constraints for Polymorphic associations. I am looking into this but I created an issue here as I suspect there might be similar issues related to the usage of Query constraints.

# frozen_string_literal: true

require "bundler/inline"

gemfile(true) do
  source "https://rubygems.org"

  git_source(:github) { |repo| "https://github.com/#{repo}.git" }

  gem 'rails', '7.1'
  gem 'sqlite3'
  gem 'pry'
end

require "active_record"
require "logger"
require 'minitest/autorun'

ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: ':memory:')

ActiveRecord::Schema.define do
  create_table :comments, force: true do |t|
    t.integer :tenant_id
    t.references :commentable, polymorphic: true, null: false
    t.string :body
    t.integer :position
  end

  create_table :authors, force: true do |t|
    t.integer :tenant_id
  end
end

class Author < ActiveRecord::Base
  query_constraints :tenant_id, :id

  has_many :comments, as: :commentable
end 

class Comment < ActiveRecord::Base
  query_constraints :tenant_id, :id

  belongs_to :commentable, polymorphic: true
end

class BugTest < Minitest::Test
  # Case when Author with tenant_id exists
  def test_when_id_exists
    author_1 = Author.create!(tenant_id: 1)
    author_2 = Author.create!(tenant_id: 1)
    comment = Comment.create(tenant_id: 1, commentable_id: author_2.id, commentable_type: 'Author')

    # BUG: Makes a query with tenant_id
    assert_equal author_2.id, comment.commentable.id 
  end

  # Case when Author with tenant_id does not exist
  def test_when_id_does_not_exist
    author = Author.create!(tenant_id: 11)
    comment = Comment.create(tenant_id: 11, commentable_id: author.id, commentable_type: 'Author')

    assert_equal author.id, comment.commentable&.id 
  end
end

Expected behavior

Actual behavior

System configuration

Rails version: 7.1.2

Ruby version: 2.7.8

@fatkodima
Copy link
Member

Was able to reproduce and figure out the solution. Going to open a PR.

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

Successfully merging a pull request may close this issue.

2 participants