ruby-on-rails – 在UUID和整数字段上的多态关联
给定整数和uuid主键的表格集成多态连接(has_many)的最佳方式是什么?例如:
class Interest < ActiveRecord::Base # id is an integer has_many :likes,as: :likeable end class Post < ActiveRecord::Base # id is a UUID has_many :likes,as: :likeable end class User < ActiveRecord::Base has_many :likes has_many :posts,through: :likes,source: :likeable,source_type: "Post" has_many :interests,source_type: "Interest" end class Like < ActiveRecord::Base # likeable_id and likeable_type are strings belongs_to :likeable,polymorphic: true belongs_to :user end 许多查询工作: interest.likes post.likes user.likes 然而: user.interests 得到:
什么是最好的方式来确保正确的铸造发生? 解决方法
我对ActiveRecord不是很好,这绝对不是你要找的答案,但如果你需要一个临时的*丑恶的解决方法,直到找到一个解决方案,你可以覆盖getter:
class User def interests self.likes.select{|like| like.likeable._type == 'Interest'}.map(&:likeable) end end *非常丑,因为它将加载所有用户喜欢,然后排序 编辑我发现this interesting article: self.likes.inject([]) do |result,like| result << like.likeable if like.likeable._type = 'Interest' result end (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |