activerecord-hackery / ransack

Object-based searching.
https://activerecord-hackery.github.io/ransack/
MIT License
5.65k stars 795 forks source link

NoMethodError raised when calling .joins(...).ransack(..._not_null: true) #1257

Open alipman88 opened 2 years ago

alipman88 commented 2 years ago

I'm getting a NoMethodError: undefined method `children' for nil:NilClass error when calling the following query:

Profile.joins(:plan).ransack(favorites_id_not_null: true).result

In Active Record query chains, should I expect to be able to add ransack after joins?

Here's an executable test script replicating my schema. I'm using Ruby 2.7.2.

# frozen_string_literal: true

require 'bundler/inline'

gemfile(true) do
  source 'https://rubygems.org'
  git_source(:github) { |repo| "https://github.com/#{repo}.git" }

  gem 'activerecord', '~> 6.1.0'
  gem 'sqlite3'
end

# ransack doesn't seem to load correctly unless loaded in a second inline gemfile block.
# Not sure why this is, but it's unrelated.
require 'active_record'

gemfile(true) do
  source 'https://rubygems.org'
  git_source(:github) { |repo| "https://github.com/#{repo}.git" }

  gem 'activerecord', '~> 6.1.0'
  gem 'sqlite3'
  gem 'ransack'
end

require 'minitest/autorun'
require 'logger'
require 'ransack'

ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: ':memory:')
ActiveRecord::Base.logger = Logger.new(STDOUT)

ActiveRecord::Schema.define do
  create_table :plans, force: true do |t|
  end

  create_table :profiles, force: true do |t|
    t.integer :plan_id
  end

  create_table :favorites, force: true do |t|
    t.integer :profile_id
  end
end

class Plan < ActiveRecord::Base
end

class Profile < ActiveRecord::Base
  belongs_to :plan
  has_many :favorites
end

class Favorite < ActiveRecord::Base
  belongs_to :profile
end

class BugTest < Minitest::Test
  def test_invalid_ransack_query
    Profile.joins(:plan).ransack(favorites_id_not_null: true).result
    # NoMethodError: undefined method `children' for nil:NilClass
  end
end
deivid-rodriguez commented 2 years ago

I guess this is not supported right now, but I would expect it to work, yeah.