Rails 6 ransacker 通过用户的多态关联进行过滤

Rails 6 ransacker to filter through User's polymorphic association

我正在尝试在 Active Admin Conversation 文件中创建一个过滤器,它将通过他的全名向我显示用户(用户全名 = user.first_name + user.last_name ). User 和 Conversation 通过如下多态关联关联:

class User < ApplicationRecord
  has_many :conversations, as: :sendable
end

class Conversation < ApplicationRecord
  belongs_to :sendable, polymorphic: true
end

因为 ActiveAdmin 在后台使用 Ransack,我试图在 User 模型中声明 ransacker 并在 admin/conversations.rb 中引用它,如下所示:

#admin/conversations.rb

ActiveAdmin.register Conversation do
  filter :sendable_of_User_type_full_name_cont, as: :string, label: 'User (name)'
end

#models/user.rb
class User < ApplicationRecord
...

  ransacker :full_name, formatter: proc { |v| v.strip } do |parent|
    "#{parent.table[:first_name]} #{parent.table[:last_name]}"
  end
end

但是我收到一个错误:

NoMethodError in Admin::ConversationsController#index

undefined method `matches' for #String:0x00007fa90ceb6560

Did you mean? match match?

Extracted source (around line #33): 31 arel_pred = arel_predicate_for_attribute(attribute) 32 arel_values = formatted_values_for_attribute(attribute) 33 predicate = attr_value_for_attribute(attribute).public_send(arel_pred, arel_values) 34 35 if in_predicate?(predicate) 36 predicate.right = predicate.right.map do |pr|

对于那些遇到类似问题的人 - 我在 docs

中找到了很好的解释

Ransnacker 进行相应更改即可解决问题:

# models/users.rb
ransacker :full_name do |parent|
  Arel::Nodes::InfixOperation.new('||',
    parent.table[:first_name], parent.table[:last_name])
end