Search code examples
ruby-on-railsruby-on-rails-3modelransack

Unransackable attributes for multiple models


To exclude some attributes from search and sorting I add following to my model

UNRANSACKABLE_ATTRIBUTES = %w[id created_at updated_at section] 

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

Two of my models use this, so what is the way to keep my code DRY and write this method once?


Solution

  • This can be done next way:

    1) uncomment config.autoload_paths += %W(#{config.root}/extras) in 'config/application.rb' and change 'extras' to 'lib'

    2) in 'lib' directory create '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) Add 'include' to models

    class Ad < ActiveRecord::Base
        include RansackableAttributes
    



    class Category < ActiveRecord::Base
        include RansackableAttributes