Skip to content

Commit 0d8db3b

Browse files
authored
Merge pull request #800 from mataki/fix-join-not-null
Fix query of not_null with joining association
2 parents f749d08 + bfebca2 commit 0d8db3b

File tree

2 files changed

+29
-2
lines changed

2 files changed

+29
-2
lines changed

lib/ransack/adapters/active_record/ransack/nodes/condition.rb

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,14 @@ def arel_predicate
77
association = attribute.parent
88
if negative? && attribute.associated_collection?
99
query = context.build_correlated_subquery(association)
10-
query.where(format_predicate(attribute).not)
1110
context.remove_association(association)
12-
Arel::Nodes::NotIn.new(context.primary_key, Arel.sql(query.to_sql))
11+
if self.predicate_name == 'not_null' && self.value
12+
query.where(format_predicate(attribute))
13+
Arel::Nodes::In.new(context.primary_key, Arel.sql(query.to_sql))
14+
else
15+
query.where(format_predicate(attribute).not)
16+
Arel::Nodes::NotIn.new(context.primary_key, Arel.sql(query.to_sql))
17+
end
1318
else
1419
format_predicate(attribute)
1520
end

spec/ransack/predicate_spec.rb

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -329,6 +329,28 @@ module Ransack
329329
field = "#{quote_table_name("people")}.#{quote_column_name("name")}"
330330
expect(@s.result.to_sql).to match /#{field} IS NULL/
331331
end
332+
333+
describe 'with association qeury' do
334+
it 'generates a value IS NOT NULL query' do
335+
@s.comments_id_not_null = true
336+
sql = @s.result.to_sql
337+
parent_field = "#{quote_table_name("people")}.#{quote_column_name("id")}"
338+
expect(sql).to match /#{parent_field} IN/
339+
field = "#{quote_table_name("comments")}.#{quote_column_name("id")}"
340+
expect(sql).to match /#{field} IS NOT NULL/
341+
expect(sql).not_to match /AND NOT/
342+
end
343+
344+
it 'generates a value IS NULL query when assigned false' do
345+
@s.comments_id_not_null = false
346+
sql = @s.result.to_sql
347+
parent_field = "#{quote_table_name("people")}.#{quote_column_name("id")}"
348+
expect(sql).to match /#{parent_field} NOT IN/
349+
field = "#{quote_table_name("comments")}.#{quote_column_name("id")}"
350+
expect(sql).to match /#{field} IS NULL/
351+
expect(sql).to match /AND NOT/
352+
end
353+
end
332354
end
333355

334356
describe 'present' do

0 commit comments

Comments
 (0)