在Ransack中,在模型更新时动态更新ranackers

问题描述 投票:0回答:1

我有公司客户和CompanyCustomerField模型。客户将hstore值存储在“属性”列中 - 密钥来自CompanyCustomerField#name字段。当一个新的CompanyCustomerField被创建时,我需要将#name添加到ransack以使它们可搜索。

当添加一个新的CompanyCustomerField时,我会转到搜索表单

undefined method `*_cont' for #<Ransack::Search:0x00007ff670100978>

因为新字段不可用于搜索。如果我关闭我的失败服务器并重新启动它是有效的,因为它让它进入搜索范围。我不知道如何动态地将功能添加到ransack中。任何想法都非常感激。

Customer.rb。这会将所有可搜索的字段放入搜索范围,但在添加新字段时不会更新它。因为这只被调用一次。

class Customer < ApplicationRecord
  # ['favorite_color', 'receive_email_marketing' etc etc]
  CompanyCustomerField.pluck(:name).each do |name|
    ransacker name.to_sym do |parent|
      Arel::Nodes::InfixOperation.new('->', parent.table[:properties], Arel::Nodes.build_quoted(name))
    end
  end
end

这是搜索表单:

#customers/index.html
<%= search_form_for @search, remote: true do |f| %>
  <% current_company.customer_fields.each do |field| %>
    <%= render "customers/search_fields/#{field.field_type}", f: f, field: field %>
  <% end %>
<% end %>

#customers/search_fields/text_field
<%= f.label (field.name + "_cont").to_sym, field.name.humanize %>
<%= f.text_field (field.name + "_cont").to_sym %>

.... 即使移动重装到控制器,仍然是相同的结果。

CustomersController.rb

def index
  Customer.reload_ransacker
  @search = current_company.customers.includes(:owner).ransack(params[:q])
  @customers = @search.result.page(params[:page])
end

Customer.rb

def self.reload_ransacker
  puts "==="
  puts "reload ransacker"
  puts "==="
  CompanyCustomerField.pluck(:name).each do |name|
    ransacker name.to_sym do |parent|
      Arel::Nodes::InfixOperation.new('->', parent.table[:properties], Arel::Nodes.build_quoted(name))
    end
  end
end
ActionView::Template::Error (undefined method `foo_cont' for #<Ransack::Search:0x00007fba3c05d5b8>):
ruby-on-rails ransack arel hstore
1个回答
0
投票

解:

需要覆盖:

module Ransack
  module Adapters
    module ActiveRecord
      module Base
        def ransacker(name, opts = {}, &block)
          @ransackable_attributes = nil
          self._ransackers = _ransackers.merge name.to_s => Ransacker
            .new(self, name, opts, &block)
        end
      end
    end
  end
end

@ransackable_attributes需要重置为nil所以在def ransackable_attributes(auth_object = nil)中,实例var是零并且可以重新加载

应该被视为搜身中的一个错误。

© www.soinside.com 2019 - 2024. All rights reserved.