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

时间:2019-02-21 19:27:15

标签: ruby-on-rails ransack arel hstore

我有Company Customer和CompanyCustomerField模型。客户将hstore值存储在“属性”列中-键来自CompanyCustomerField#name字段。创建新的CompanyCustomerField时,我需要将#name添加到ransack中以使其可搜索。

添加新的CompanyCustomerField时,我进入搜索表单

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

因为新字段不可用于搜索。如果我关闭了失败的服务器并重新启动,则它可以工作,因为它进入了rasack。 我不知道如何将功能动态添加到ransack中。任何想法表示赞赏。

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

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>):

1 个答案:

答案 0 :(得分: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为nil并且可以重新加载

应该被认为是抢劫中的错误。