我在试图将Rails 4,STI,多态关联与has_many :::
结合起来时遇到了问题问题:UserConnection未根据STI保存正确的userable_type
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应该是&#34; Post&#34;但它&#34;出版&#34;。
我尝试根据所有类似的StackOverflow问题添加以下内容:
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
这没有帮助。
任何想法都将非常感谢
答案 0 :(得分:1)
证明这是一个尚未解决的旧问题
https://github.com/rails/rails/issues/724
https://github.com/rails/rails/issues/6786
宝石补丁解决方案: https://github.com/appfolio/store_base_sti_class
使用您的代码测试它并且它可以正常工作。