Search code examples
ruby-on-railsransack

ransack_alias not doing anything in query


I use Ransack for my search forms and I am attempting to use ransack_alias to shorten the queries. However, when I perform a search, the aliased fields don't filter the query at all. I have simplified my form to have only one simple alias and it doesn't seem to work.

user model

class User < ActiveRecord::Base
  ransack_alias :ec, :email_cont
end

index.html.haml

= search_form_for @q, url: users_path, html: {method: :get} do |f|
  = f.label :ec
  = f.search_field :ec
  = f.submit 'Search'

If I put a breakpoint inside the controller:

>> User.count
10

>> User.ransack({email_cont: "test@email.com"}).result.count
(93.8ms)  SELECT COUNT(*) FROM "users" WHERE ("users"."email" ILIKE '%test@email\.com%')
1

>> params[:q]
{"ec" => "test@email.com"}

>> User.ransack(params[:q]).result.count
(28.4ms)  SELECT COUNT(*) FROM "users"
10

>> User._ransack_aliases
{"ec" => "email_cont"}

What am I doing wrong here?


Solution

  • ransack_alias is for aliasing attributes, but not comparison key.

    class User < ActiveRecord::Base
      ransack_alias :e, :email
    end
    
    > User.ransack({'e_cont' => "user"}).result.count 
    (0.2ms)  SELECT COUNT(*) FROM "users" WHERE ("users"."email" LIKE '%user%')