简体   繁体   中英

Rails 6 ransacker to filter through User's polymorphic association

I'm trying to create a filter inside of Active Admin Conversation file, which will show me the User by his full name (user full name = user.first_name + user.last_name). User and Conversation are related by polymorphic association like below:

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

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

Because ActiveAdmin use Ransack under the hood I was trying to declare ransacker inside of User model and refer to it in admin/conversations.rb , like below:

#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

But I'm getting an error:

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|

For those struggling with a similar problem - I found a nice explanation in the docs

Ransnacker change accordingly will do the trick:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM