2013-03-12 56 views
0

Unransackable属性,从搜索中排除某些属性和分类我添加以下到我的模型多个型号

UNRANSACKABLE_ATTRIBUTES = %w[id created_at updated_at section] 

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

我的模型的两个使用,所以是什么让我的代码干,写这个方法的方式一旦?

回答

1

这是可以做到下方式:

1)取消注释config.autoload_paths + =%W(#{config.root} /演员)的 '配置/ application.rb中' 和变化 '附加' 到'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 
0

我知道这是旧的,但我想分享一下我在你不希望在所有的车型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 
+0

谢谢替代方法 – Berlin 2013-12-05 17:41:53

+0

您的欢迎,虽然请知道这种方法是皱起了眉头皱了皱眉由厄尔(ransack的创造者)提供。我也扩大了实施见更新 – engineersmnky 2013-12-05 21:40:53