Search code examples
ruby-on-railsrubyactiveadminarelransack

Ransacker and Arel on associations fields


I have Project::Contribution that belongs_to User, and User has_one User::Profile.

first_name and last_name are fields contained in User::Profile

I want to create a ransacker that would allow me to filter my contributions with their user profile first_name and last_name.

How can this be achieved ?

This is what I tried so far :

# admin/contribution.rb
filter :user_full_name_cont

# models/user.rb
ransacker :full_name do |parent|
  Arel::Nodes::InfixOperation.new('||', parent.table[:profile_first_name], parent.table[:profile_last_name]) # error
end

This fails because of : parent.table[:profile_first_name] and parent.table[:profile_last_name] because I can't access the profile table like so.


Solution

  • Finally came to a solution :

    # models/user/profile.rb
      ransacker :full_name, formatter: proc { |v| v.mb_chars.downcase.to_s } do |parent|
        Arel::Nodes::NamedFunction.new('LOWER',
         [Arel::Nodes::NamedFunction.new('concat_ws',
          [Arel::Nodes.build_quoted(' '), parent.table[:first_name], parent.table[:last_name]])])
      end
    
    # admin/user.rb
    filter :user_profile_full_name_cont