Kev*_*tre 20 postgresql ruby-on-rails
给定表integer和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, through: :likes, source: :likeable, source_type: "Interest"
end
class Like < ActiveRecord::Base
# likeable_id and likeable_type are strings
belongs_to :likeable, polymorphic: true
belongs_to :user
end
Run Code Online (Sandbox Code Playgroud)
许多查询都有效:
interest.likes
post.likes
user.likes
Run Code Online (Sandbox Code Playgroud)
然而:
user.interests
Run Code Online (Sandbox Code Playgroud)
得到:
PG :: UndefinedFunction:ERROR:运算符不存在:integer =字符变化LINE 1:...兴趣"INNER JOIN"喜欢"ON"兴趣"."id"="喜欢".... ^提示:没有运算符匹配给定的名称和参数类型.您可能需要添加显式类型转换.:SELECT"interests".*FROM"interests"INNER JOIN"likes"ON"interest"."id"="likes"." likeable_id"WHERE"喜欢"."user_id"= $ 1 AND"喜欢"."likeable_type"= $ 2
包括确保正确铸造发生的最佳方法是什么?
Cyr*_*ris -4
我不擅长 ActiveRecord,这绝对不是您正在寻找的答案,但如果您需要一个临时的*丑陋的解决方法,直到找到解决方案,您可以覆盖 getter :
class User
def interests
self.likes.select{|like| like.likeable._type == 'Interest'}.map(&:likeable)
end
end
Run Code Online (Sandbox Code Playgroud)
*非常难看,因为它会加载所有用户喜欢的内容,然后对它们进行排序
编辑我发现这篇有趣的文章:
self.likes.inject([]) do |result, like|
result << like.likeable if like.likeable._type = 'Interest'
result
end
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1076 次 |
| 最近记录: |