我知道这很旧,但我想分享我的处理方式,以防您不想在所有模型中都有 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