我在搜索关系字段时遇到了搜索问题。我的模型如下:
ListView<String>
在控制器中,索引操作负责搜索:
# 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
根据有关搜查的文件:cellFactory
search_form_for如下:
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
运行此代码会导致错误:Ransack :: Search&gt;的未定义方法`user_phone_cont':Ransack :: Search
我尝试将索引操作更改为如下:= 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'
但是这不起作用并导致相同的错误。我试图将text_field更改为search_field,结果相同。我还尝试在2行上建立用户关系,通过在Pass模型中添加以下行来修改Pass模型中的关系来区分用户是User和其他任何人:@passes = @query.result.includes(:user).page(page)
然后修改表单是normal_user_phone_cont,并且导致与未定义的属性/方法的命名更改相同的错误。
任何帮助将不胜感激,并提前感谢您阅读该问题。
答案 0 :(得分:2)
我认为使用Ransack搜索多态关系有一些约定,如以下链接所述: https://github.com/activerecord-hackery/ransack/wiki/Polymorphic-searches
根据您的情况,您应该使用以下约定:user_of_user_type_phone
,以便仅搜索用户。