Search code examples
ruby-on-railsruby-on-rails-4ransack

Searching polymorphic relation using ransack gem


I am having an issue with ransack while searching for a relation field. My models are as follows:

# Model to search in
class Pass < ActiveRecord::Base
    belongs_to :user, polymorphic: true
    belongs_to :admin
    belongs_to :last_owner, polymorphic: true
end

# User class having phone
class User < ActiveRecord::Base
    has_many :passes
    has_many :owned_passes, class_name: 'Pass', foreign_key: 'owner_id'
    has_many :last_owned_passes, class_name: 'Pass', foreign_key: 'last_owner_id'
end

# Doesn't have phone column
class Admin < ActiveRecord::Base
    has_many :passes
    has_many :owned_passes, as: :owner, class_name: 'Pass', foreign_key: :owner_id
    has_many :last_owned_passes, as: :last_owner, class_name: 'Pass', foreign_key: :last_owner_id
end

#Doesn't have phone column
class Moderator < Admin
end

In the controller, the index action is responsible for the searching:

class Dashboard::PassesController < Dashboard::BaseController
    def index
        @query  = scope.search(params[:q])
        @passes = @query.result(distinct: true).page(page)
    end
private
    def scope
        scope = current_dashboard_admin.passes
        scope = scope.where(parent_id: params[:parent_id]) if params.key? :parent_id
        scope = scope.order(created_at: :desc)
        scope = scope.where(type: 'Pass')
        scope
    end
end

As per the documentation on ransack: https://github.com/activerecord-hackery/ransack The search_form_for is as follows:

= search_form_for [:dashboard, @query] do |f|
  .form-body
     .form-group
       = f.label :user_phone_cont
       = f.text_field :user_phone_cont, class: 'form-control'

Running this code results in the error: undefined method `user_phone_cont' for Ransack::Search>:Ransack::Search

I tried to change the index action to be as follows: @passes = @query.result.includes(:user).page(page) but that didn't work and resulted in the same error. I tried to change the text_field to search_field, same result. I also tried having the user relation on 2 lines to differentiate between the user who's class is User and anyone else by modifying the relation in the Pass model by adding the following line to the Pass model: belongs_to :normal_user, -> { where(user_type: 'User') } and then modified the form to be normal_user_phone_cont, and that resulted in the same error with the change in the naming for the attribute/method that's undefined.

Any help would be appreciated, and thank you in advance for reading the question.


Solution

  • I think searching Polymorphic relations using Ransack has some convention to follow as stated in the following link : https://github.com/activerecord-hackery/ransack/wiki/Polymorphic-searches

    for your situation you should use the following convention: user_of_user_type_phone in order to search users only.