It's gonna get a bit tricky.
So, I have a forum app consisting of Section
entities. And the forum also has Char
entities (who write posts and create topics) and CharGroup
entities for grouping chars. The sections can be set to private access.
Then I got to access permisions to those private sections. I have an SectionAccess
class with STI that can be either Access::Char
or Access::Group
, providing access to individual chars and char_groups accordingly. They all have a section_id
field linking them to a section and an access_id
field, linking to either char or a char_group (and a type
field for STI of cource).
class Access::Char < Access
belongs_to :char, class_name: '::Char', foreign_key: :access_id
end
class Access::Group < Access
belongs_to :group, class_name: 'CharGroup`, foreign_key: :access_id
end
Now I'm trying to link those up in the Section
class.
class Section < ApplicationRecord
...
has_many :access_chrs, class_name: 'Access::Char'
has_many :access_chars, class_name: '::Char', through: :access_crhs, source: :char
# I need the :chars accociation for something else here
has_many :access_grps, class_name: 'Access::Group'
has_many :access_groups, class_name: 'CharGroup', through: :access_grps, source: :group
...
end
And this is where I bump into a problem. The access_chars
association wotks perfectly fine, allowing to read and write with no problem at all.
The access_groups
association works fine on reading (e.g. section.access_groups
and section.access_group_ids
) and even building (if I call section.access_groups.new
I get a new CharGroup
record), but not for writing. No matter how I try to write on this relation (e.g. section.access_groups << CharGroup.first
, section.access_group_ids << CharGroup.first.id
, section.access_group_ids = [1]
or anything else) it gives me an error ActiveRecord::AssociationTypeMismatch: ::Char(#45301460) expected, got #<CharGroup...
.
Even if I try to do section.access_groups.create name: 'Foo'
it creates the CharGroup record, but then raises the error on trying to associate it.
Is there any probable solutions other then redefining the methods I need?