【发布时间】:2014-12-16 14:56:39
【问题描述】:
我在尝试将 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
这没有帮助。
任何想法将不胜感激
【问题讨论】:
-
User是否还有其他不在Publication的继承树中的UserConnection?也许这里不需要多态userable。 -
是的。 UserConnection 旨在与发布以外的其他类一起使用。
标签: ruby ruby-on-rails-4 has-many-through polymorphic-associations sti