0

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.

3
  • If I understood this right, you will need to initialize this @bar somewhere. Since you are using it in many controllers do it in application controller. Commented Apr 3, 2015 at 12:24
  • Where is your @bar defined? You should have a method like def find_bar @bar = Bar.find(params[:id]); end somewhere. Commented Apr 3, 2015 at 12:53
  • @ForgetTheNorm, "bar" is defined in a "before_action". The "bar" is not an issue if it is in a specific controller itself. The problem arises when I move these methods to a more generic concern. I can't call "bar" in the concern as I need to use the Concern for "baz" as well. Commented Apr 3, 2015 at 13:17

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.