many belongs_to and has_many in single line

1.3k Views Asked by At

Hi I am working on one application which has so many relations on the model. Now I am thinking to reduce line of code and I find so many relations like has_many and belongs_to.

Can we have singe line where we can write something like

belongs_to [:comment, :rating, :indication], dependent: :destroy

belongs_to :travels, foreign_key: travel_item_id

1

There are 1 best solutions below

1
iMacTia On BEST ANSWER

Unfortunately, not. AFAIK this is not possible and even the documentation doesn't seems to allow this. What you can do, is to define a metaprogramming method that iterate over an array and create this associations. But not sure if it worth it.

EDIT

Just an example of what I mean by metaprogramming method Create a file app/models/concerns/associate.rb

module Associate
  extend ActiveSupport::Concern

  module ClassMethods
    def associate(ass_type, names = [], params = {})
      names.each do |n|
        send ass_type, n, params
      end
    end
  end
end

Then, in your model, to do the multiple belongs_to, just do

include Associate
associate :belongs_to, [:comment, :rating, :indication], dependent: :destroy