简体   繁体   English

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

[英]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).我正在尝试在 Active Admin Conversation文件中创建一个过滤器,它将通过他的全名向我显示用户(用户全名 = user.first_name + user.last_name)。 User and Conversation are related by polymorphic association like below: User 和 Conversation 通过多态关联关联,如下所示:

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:因为 ActiveAdmin 在幕后使用 Ransack,我试图在User模型中声明 ransack 并在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

But I'm getting an error:但我收到一个错误:

NoMethodError in Admin::ConversationsController#index Admin::ConversationsController#index 中的 NoMethodError

undefined method `matches' for #String:0x00007fa90ceb6560 #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|提取的源代码(围绕第 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_pred), 33_predicate if3)_value=5(in.4right3predicate) predicate.right.map 做 |pr|

For those struggling with a similar problem - I found a nice explanation in the docs对于那些遇到类似问题的人 - 我在文档中找到了一个很好的解释

Ransnacker change accordingly will do the trick: Ransnacker 相应的更改将起作用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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