简体   繁体   中英

Rails 4 Controller Concern initializer

I would like to add a status concern to various controllers since all of these controllers share the same status functionality.

A status can be "active", "inactive" or "archived". If added to a specific controller ex. bars_controller these methods would look like this:

def activate
  @bar.activate!
  redirect_to(:back)
end

def deactivate
  @bar.deactivate!
  redirect_to(:back)
end

def archive
  @bar.archive!
  redirect_to(:back)
end

I have moved the above to my concern called Foo and I've included Foo in my controller like this:

include Foo

The issue I have when moving these methods to a concern, is that the Model instance is not defined.

How do I generalize the "@bar" section of the code in my concern? This will enable me to use the concern for multiple Model instances including Baz. I tried using "self" but that references the Controller instance and not the Model instance.

Your concern could look like this:

module Foo
    extend ActiveSupport::Concern

    def activate
        render text: bar.to_json
    end

    def deactivate
        render text: bar.to_json
    end

    def archive
        render text: bar.to_json
    end

    private

    def bar
        # 'demodulize' isn't necessary if you're working outside of namespaces
        params[:controller].classify.demodulize.constantize.find(params[:id])
    end

end

And your routes would benefit from using a concern as well:

concern :statusable do
    member do
        get :activate
        get :deactivate
        get :archive
    end
end

resources :alphas, :bravos, :charlies, concerns: :statusable

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