我在尝试通过将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应该是"Post",但它是"Publication"。
我尝试根据所有类似的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
这没用。
任何想法都将非常感谢
发现这是一个尚未解决的老问题
https://github.com/rails/rails/issues/724
https://github.com/rails/rails/issues/6786
gem补丁解决方案:https://github.com/appfolio/store_base_sti_class
用你的代码测试了它,它就工作了。