I'm working on an engine where any model can have a has_many association with Permit as Permissible:
class Permit < ActiveRecord::Base
belongs_to :permissible, polymorphic: true
end
module Permissible
def self.included(base)
base.class_eval do
has_many :permits, as: :permissible
end
end
class Group < ActiveRecord::Base
include Permissible
end
class GroupAllocation < ActiveRecord::Base
belongs_to :person
belongs_to :group
end
class Person < ActiveRecord::Base
include Permissible
has_many :group_allocations
has_many :groups, through: :group_allocations
end
class User < ActiveRecord::Base
belongs_to :person
end
So, Group has_many :permits and Person has_many :permits. What I am trying to do is dynamically create associations on User that uses the permits association as a source, and chain associations on other models down to User by doing the same. This can be done manually (in rails 3.1+) with:
class Person
has_many :group_permits, through: :person, source: :permits
end
class User
has_many :person_permits, through: :person, source: :permits, class_name: Permit
has_many :person_group_permits, through: :person, source: :group_permits, class_name: Permit
end
However, in practice, Permissible will be included on many models, so I'm trying to write a class method on User (actually within another module, but no need to confuse things more) that can traverse User.reflect_on_all_associations and create an array of new associations, which may be many associations deep each.
Looking for input on how to do this cleanly in rails 3.2.8.