使用 ransack 搜索多态关系 gem

Searching polymorphic relation using ransack gem

我在搜索关系字段时遇到搜索问题。我的模型如下:

# 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

在控制器中,索引动作负责搜索:

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

根据搜查文档:https://github.com/activerecord-hackery/ransack search_form_for如下:

= 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'

运行 此代码导致错误:Ransack::Search> 的未定义方法 `user_phone_cont':Ransack::Search

我试图将索引操作更改为如下所示:@passes = @query.result.includes(:user).page(page) 但那没有用并导致了同样的错误。我尝试将 text_field 更改为 search_field,结果相同。我还尝试在 2 行上设置用户关系,以通过将以下行添加到 Pass 模型来修改 Pass 模型中的关系来区分 class 是 User 的用户和其他任何人:belongs_to :normal_user, -> { where(user_type: 'User') } 和然后将表单修改为 normal_user_phone_cont,这导致与未定义的 attribute/method 的命名更改相同的错误。

如有任何帮助,我们将不胜感激,在此先感谢您阅读该问题。

我认为使用 Ransack 搜索多态关系有一些约定要遵循,如下所述 link: https://github.com/activerecord-hackery/ransack/wiki/Polymorphic-searches

对于您的情况,您应该使用以下约定:user_of_user_type_phone 以便仅搜索用户。