gpt4 book ai didi

ruby-on-rails - UUID 和整数字段的多态关联

转载 作者:行者123 更新时间:2023-11-29 11:09:42 27 4
gpt4 key购买 nike

给定包含 integeruuid 主键的表,集成多态连接 (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

许多查询有效:

interest.likes
post.likes
user.likes

但是:

user.interests

给予:

PG::UndefinedFunction: ERROR: operator does not exist: integer = character varying LINE 1: ...interests" INNER JOIN "likes" ON "interests"."id" = "likes".... ^ HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts. : SELECT "interests".* FROM "interests" INNER JOIN "likes" ON "interests"."id" = "likes"."likeable_id" WHERE "likes"."user_id" = $1 AND "likes"."likeable_type" = $2

确保正确转换的最佳方法是什么?

最佳答案

这是一个老问题,但这是我的建议。

这更像是一个架构问题。不要组合 UUID id 和整数 id,它很快就会变得困惑。如果可以,请将整数 ID 迁移到 UUID 或将 uuid 还原为整数 ID。

我的经验是,最好的解决方案可能是使用相当不错的 Friendly ID gem:https://github.com/norman/friendly_id

在未来这被打破的情况下,它基本上只是一个 slug generation/managemnet 工具,slug 会使用这种路由路径:posts/this-is-a-potential-slug而不是 posts/1 , 但没有什么能阻止你使用 posts/<UUID here>posts/<alphanumeric string here> .

通常,如果您使用 UUID,那是因为您不想显示顺序整数。友好 ID 可以很好地避免该问题。

关于ruby-on-rails - UUID 和整数字段的多态关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31395230/

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