【问题标题】:Rails 4 - STI has_many :through with polymorphic associationRails 4 - STI has_many:通过多态关联
【发布时间】: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


【解决方案1】:

原来这是一个尚未解决的老问题

https://github.com/rails/rails/issues/724

https://github.com/rails/rails/issues/6786

gem补丁解决方案: https://github.com/appfolio/store_base_sti_class

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

【讨论】:

    猜你喜欢
    • 2016-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-28
    • 2015-11-16
    • 2013-11-24
    相关资源
    最近更新 更多