2013-03-12 52 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