Search code examples
ruby-on-railsransack

building a ransack form with saved data


I have the ransack search data saved in the DB, in form of a hash:

{"name_cont"=>"an", "c"=>{"1366814870748"=>{"a"=>{"0"=>{"name"=>"gender"}}, "p"=>"eq", "v"=>{"0"=>{"value"=>"female"}}}, "1366814890125"=>{"a"=>{"0"=>{"name"=>"shoe_size"}}, "p"=>"gt", "v"=>{"0"=>{"value"=>"2"}}}}}

Then I create a ransack form from it:

@search = Sedcard.search hash
<%= search_form_for @search %>

How can I iterate through the conditions to create selects based on the form object similar to the one presented in railscasts?


Solution

  • At the end I managed to find the proper code. It was in the ransack demo example:

    The example is a little bit complex because the first field (search field for name) is shown elsewhere and it is static so it need not to be shown twice. And ransack appends a last empty filter with nothing preselected therefore I am filtering that out too.

                = f.condition_fields do |c|
                  %div
                    - render_attribute = true
                    = c.attribute_fields do |a|
                      - regular_for_nondisplay = /\<option value=\"name\" selected\=\"selected\"\>Name\<\/option\>/
                      - regular_for_checking_not_empty = /selected=\"selected\"/
                      - filter_name = a.attribute_select
                      - if filter_name =~ regular_for_nondisplay || filter_name !~ regular_for_checking_not_empty
                        - render_attribute = false
                        -
                      - else
                        = filter_name
                      -
    
                    - if render_attribute
                      = c.predicate_select 
                      = c.value_fields do |v|
                        = v.text_field :value
                      = link_to t('.remove'), '#', class: 'remove-fields btn-a btn-error'