Mel Mel - 1 month ago 16
Ruby Question

Rails 5, Concerns - can they reference a database table?

I'm trying to learn about concerns.

Most of the blog posts and examples I can find discuss them in the context of moving class methods defined in a model to a common repository. I understand that part.

I don't understand whether concerns can be used to reduce the setup for associated models. For example, I have a user model and an organisation model. Each of user and organisation will have an address.

If address is a model, it will be polymorphic and belong to addressable. Then user and organisation will each have one address.

I am trying to understand whether I can make address a concern and then include it in my user and organisation models. If so, can I still have a table in the database called address? It's not clear to me whether I can have the db table if I don't have a model called address (which I wouldn't need if I used concerns subfolder in the models folder to define address).

Answer

Yes, you can certainly do this, and it's pretty common. You'll still need an Address model and addresses table in the database.

It would look something like this:

# your user model (backed by users table)
class User < ApplicationRecord
   include Addressable
end

# your organisation model (backed by organisations table)
class Organisation < ApplicationRecord
  include Addressable
end

# your address model (backed by addresses table)
class Address < ApplicationRecord
  belongs_to :addressable, polymorphic: true, touch: true
end

# the concern to DRY up shared relation that both user adn organisation have
module Addressable
  extend ActiveSupport::Concern

  included do
    has_one :address, as: :addressable, dependent: :destroy
  end
end
Comments