gpt4 book ai didi

ruby - Rails 4 - STI has_many :through with polymorphic association

转载 作者:太空宇宙 更新时间:2023-11-03 16:25:00 26 4
gpt4 key购买 nike

我在尝试将 Rails 4、STI、多态关联与 has_many: :through 结合时遇到问题

问题: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

用您的代码对其进行了测试,它可以正常工作。

关于ruby - Rails 4 - STI has_many :through with polymorphic association,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26485763/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com