How to use model concerns in rails

1.8k views Asked by At

I am trying to move different parts of a model into concerns. Two of each are the states defined by AASM, and attachments with Paperclip.

So, I am moving the related codes into separate files.

app/models/concerns/user_aasm.rb

class User
    module UserAasm
        extend ActiveSupport::Concern
        included do
            include AASM
            aasm do
            state :unverified, initial: true
            state :approved
            state :suspended
            state :deleted
            state :banned
          end
        end
    end
end

and in my user.rb, I do

include UserAasm

I got the following error:

Unable to autoload constant UserAasm, expected app/models/concerns/user_aasm.rb to define it

I wonder what I got wrong in the code.. How to use it in a correct way?

2

There are 2 answers

0
Nermin On BEST ANSWER

You need to define it like.

require 'active_support/concern'

module UserAasm
    extend ActiveSupport::Concern
    included do
        include AASM
        aasm do
        state :unverified, initial: true
        state :approved
        state :suspended
        state :deleted
        state :banned
      end
    end
end

Then in your User model

include UserAasm

This is not the right way to make your model skiny, because concerns folder is used to put code that is shared among more models. You should put modules that implement some behaviour, not extract code from your model and put it inside concerns

Read this article from CodeClimate

Quote from this link.

'Using mixins like this is akin to “cleaning” a messy room by dumping the clutter into six separate junk drawers and slamming them shut. Sure, it looks cleaner at the surface, but the junk drawers actually make it harder to identify and implement the decompositions and extractions necessary to clarify the domain model.'

0
karlingen On

The module needs to be defined outside the class.

So inside app/models/concerns/user_aasm.rb:

module UserAasm
  extend ActiveSupport::Concern
  included do
    include AASM
    aasm do
    state :unverified, initial: true
    state :approved
    state :suspended
    state :deleted
    state :banned
    end
  end
end