我知道這是舊的,但我想分享一下我在你不希望在所有的車型UNRANSACKABLE_ATTRIBUTES事件處理這種方式。我創建了擴展的ActiveRecord的Ransacks模塊:: Base的
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
這些屬性不會ransackable。我喜歡這種方法,因爲它可以讓你有條件地設置它們。
編輯
雖然在爲Class魔術這樣做對於那些你的工作,不介意
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
謝謝替代方法 – Berlin 2013-12-05 17:41:53
您的歡迎,雖然請知道這種方法是皺起了眉頭皺了皺眉由厄爾(ransack的創造者)提供。我也擴大了實施見更新 – engineersmnky 2013-12-05 21:40:53