diff --git a/lib/ransack/nodes/grouping.rb b/lib/ransack/nodes/grouping.rb index 1bf705508..65843c029 100644 --- a/lib/ransack/nodes/grouping.rb +++ b/lib/ransack/nodes/grouping.rb @@ -178,10 +178,28 @@ def write_attribute(name, val) end def read_attribute(name) - if self[name].respond_to?(:value) - self[name].value + # First try to find condition with the exact name (including aliases) + condition = self[name] + + # If not found and the name might be an alias, try the resolved attribute name + if condition.nil? + # Strip predicate and resolve alias, similar to condition extraction logic + str = name.to_s.dup + require_relative '../predicate' + predicate_name = Predicate.detect_and_strip_from_string!(str) + resolved_base = @context.ransackable_alias(str) + + if resolved_base != str + # Reconstruct the full attribute name with predicate + resolved_name = predicate_name ? "#{resolved_base}_#{predicate_name}" : resolved_base + condition = self[resolved_name] + end + end + + if condition.respond_to?(:value) + condition.value else - self[name] + condition end end diff --git a/spec/ransack/helpers/form_builder_spec.rb b/spec/ransack/helpers/form_builder_spec.rb index 90b01c138..7ecff59a5 100644 --- a/spec/ransack/helpers/form_builder_spec.rb +++ b/spec/ransack/helpers/form_builder_spec.rb @@ -153,6 +153,19 @@ module Helpers end end + context 'search field values with aliases' do + before do + @controller.view_context.search_form_for(Person.ransack(term_cont: 'test_value')) { |f| @f = f } + end + + it 'should persist alias field value in search forms' do + # This tests that when a search is created with an alias parameter, + # the form field using that alias should show the correct value + html = @f.search_field(:term_cont) + expect(html).to match /value="test_value"/ + end + end + private def test_label(f, query, expected)