Reputation: 574
I'm have an issue trying to combine Rails 4, STI, polymorphic associations with has_many: :through
The issue: UserConnection is not saving the correct userable_type according to the STI
class UserConnection < ActiveRecord::Base
belongs_to :userable, polymorphic: true
belongs_to :user
end
class User < ActiveRecord::Base
has_many :user_connections
has_many :tagged_posts, through: :user_connections, class_name: 'Post', source: :userable, source_type: 'Post'
end
class Publication < ActiveRecord::Base
has_many :user_connections, as: :userable, dependent: :destroy
has_many :users, through: :user_connections
end
class Post < Publication
end
Post.create(user_ids: [1, 2], body: 'yo')
UserConnection.last
=> #<UserConnection id: 1, user_id: 2, userable_id: 44, userable_type: "Publication">
userable_type should be "Post" but it's "Publication".
I tried adding the following according to all the similar StackOverflow questions:
class UserConnection < ActiveRecord::Base
belongs_to :userable, polymorphic: true
belongs_to :user
def userable_type=(class_name)
super(class_name.to_s.classify.constantize.base_class.to_s)
end
end
This didn't help.
Any ideas will greatly appreciated
Upvotes: 2
Views: 1692
Reputation: 447
turns out it's an old issue that wasn't solved yet
https://github.com/rails/rails/issues/724
https://github.com/rails/rails/issues/6786
gem patch solution: https://github.com/appfolio/store_base_sti_class
tested it with your code and it works.
Upvotes: 1