1

为了从搜索和排序中排除某些属性,我将以下内容添加到我的模型中

UNRANSACKABLE_ATTRIBUTES = %w[id created_at updated_at section] 

def self.ransackable_attributes auth_object = nil
    (column_names - UNRANSACKABLE_ATTRIBUTES) + _ransackers.keys
end

我的两个模型都使用了这个,那么保持我的代码 DRY 并编写一次这个方法的方法是什么?

4

2 回答 2

1

这可以通过以下方式完成:

1) 在 'config/application.rb' 中取消注释 config.autoload_paths += %W(#{config.root}/extras) 并将 'extras' 更改为 'lib'

2)在“lib”目录中创建“ransackable_attributes.rb”:

module RansackableAttributes
    extend ActiveSupport::Concern

    included do
        def self.ransackable_attributes auth_object = nil
            (column_names - self::UNRANSACKABLE_ATTRIBUTES) + _ransackers.keys
        end
    end

end

3) 在模型中添加“包含”

class Ad < ActiveRecord::Base
    include RansackableAttributes



class Category < ActiveRecord::Base
    include RansackableAttributes
于 2013-03-17T07:58:46.053 回答
1

我知道这很旧,但我想分享我的处理方式,以防您不想在所有模型中都有 UNRANSACKABLE_ATTRIBUTES。我创建了一个初始化器,它扩展了 ActiveRecord::Base 的 Ransacks 模块

module Ransack
  module Adapters
    module ActiveRecord
      module Base
        attr_accessor :_spare
        def spare_ransack(*attribs)
          self._spare = attribs.map{|a| a.to_s}
        end
        def spareables
          self._spare ||= []
          column_names - self._spare
        end
        def ransackable_attributes(auth_object = nil)
          spareables + _ransackers.keys
        end
      end
    end
  end
end

然后你可以使用

MyClass < ActiveRecord::Base
  spare_ransack :id, :created_at, :updated_at, :section
end

而且这些属性不会被洗劫。我喜欢这种方法,因为它允许您有条件地设置它们。

编辑

虽然不被视为职业魔法,但这确实适用于那些不介意的人

def spare_ransack(*attribs)
  self._spare = attribs.map do |a| 
    case a.to_sym
      #remove time_stamp fields 
        when :time_stamps
          ["created_at","updated_at"]
      #requires spare_ransack to be called after associations in the file
        when :association_keys
          reflect_on_all_associations.select{|a| a.macro == :belongs_to}.collect{|a| a.options[:foreign_key] || "#{a.name}_id"}
      #remove primary key field 
        when :primary
          primary_key
        else
          a.to_s
    end
  end.flatten
end

MyClass < ActiveRecord::Base
  spare_ransack :primary,:time_stamps, :section
end
于 2013-11-18T16:56:09.123 回答