开发者

Rails: "invalid byte sequence in UTF-8" exception when setting up a has_one association by UUID

开发者 https://www.devze.com 2023-02-12 10:36 出处:网络
Environment: Ruby 1.9.2, Rails 3.0.1 Two MySQL tables: 1. items, 2. vote_counts (every row represents the number of users who voted on an item)

Environment: Ruby 1.9.2, Rails 3.0.1

Two MySQL tables: 1. items, 2. vote_counts (every row represents the number of users who voted on an item)

Since the tables are bi开发者_运维知识库g and I need to shard them, I am using UUIDs. The uuid column is defined in both tables: uuid varbinary(16) NOT NULL.

I defined a has_one association in item model: has_one :vote_count, :foreign_key => "uuid", :primary_key => "uuid"

When I call item.vote_count, I am getting the following exception on some UUID values: "ArgumentError: invalid byte sequence in UTF-8".

Of course the raw UUID is just a sequence of bytes (Encoding:ASCII-8BIT), but when ActiveRecord constructs a SQL query, it tries to interpret it as a UTF-8 string.

How can I tell it to just pass the byte sequence to MySQL?


Are you using something like

UUIDTools::UUID.random_create.hexdigest[0, 8]

to generate the UUID?

We use this and we assign it to a string field in our models using both mysql and postgres DBs. note: we are not using them as keys. Just as regular fields in the model.

0

精彩评论

暂无评论...
验证码 换一张
取 消