rico_mac
rico_mac

Reputation: 888

Rails shared controller actions

I am having trouble building a controller concern. I would like the concern to extend the classes available actions.

Given I have the controller 'SamplesController'

class SamplesController < ApplicationController
  include Searchable
  perform_search_on(Sample, handle: [ClothingType, Company, Collection, Color])
end

I include the module 'Searchable'

module Searchable
  extend ActiveSupport::Concern

  module ClassMethods
    def perform_search_on(klass, associations = {})
       .............
    end

    def filter
      respond_to do |format|
        format.json { render 'api/search/filters.json' }
      end
    end
  end
end

and, despite setting up a route i get the error 'The action 'filter' could not be found for SamplesController'.

I thought it might be to do with wether I include, or extend the module. I tried using extend but that also gave the same error.

I still need to be able to feed the module some configuration options on a per controller basis. Is it possible to achieve what I am trying to do here?

Any help appreciated, thanks

Upvotes: 1

Views: 1151

Answers (2)

Roman Kiselenko
Roman Kiselenko

Reputation: 44380

You should pass actions to the included block and perform_search_on to the class_methods block.

module Searchable
  extend ActiveSupport::Concern

  class_methods do
    def perform_search_on(klass, associations = {})
       .............
    end
  end      

  included do
    def filter
      respond_to do |format|
        format.json { render 'api/search/filters.json' }
      end
    end

  end
end

When your Searchable module include a method perform_search_on and the filter action.

Upvotes: 4

cortex
cortex

Reputation: 5224

Try removing the methods from the module ClassMethods. That is making them instance methods.

Upvotes: 1

Related Questions