Using Concerns in Ruby on Rails Development

8 Feb 2013, by Michael Cindrić

Concerns are a great way to mix in common model behaviours and keep your code clean and not have to resort to STI.

So lets take a look at what a concern looks like. Below l have a Module called "Auditable" which extens ActiveSupport Concern.

The purpose of this is to record statistics on objects as they are created and destroyed. Now this comes in handy when you want to analyse how your customers are using your ruby on rails application.

module Auditable
  extend ActiveSupport::Concern

  included do
    has_many          :audits, as: :auditable

    after_create      :record_creation
    before_destroy    :record_deletion 

  def record_creation

  def record_deletion


That module gives any Active Recored model that includes it the instant ability to track when its deleted or created via a Audit record which you can see Auditable can have many of. Anything included in the include block below acts on the model the same as if you where to call has_many or validates within the model itself

included do
  // Declarations go here

The last step is to include the concern in your model like so

  include Auditable

Now some people say you have to load the folder app in application.rb, this is not the case if you store your concerns like we do under "app/concerns". This keeps them in the right place and also does not require you to specify them in the app.rb file

Cookies help us deliver our services. By using our services, you agree to our use of cookies.