简体   繁体   中英

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM