我有一个相当简单的查询来返回多对多关系中的第一条记录,或者如果它不存在则创建一个。
UserCategorization.where(category_id: 3, user_id: 5).first_or_create
我的模型看起来像:
class UserCategorization < ActiveRecord::Base
belongs_to :user
belongs_to :category
self.primary_key = [:user_id, :category_id]
end
但是,它会在 SQL 中生成无效的列名:
SQLite3::SQLException: no such column: user_categorizations.[:user_id, :category_id]:
SELECT "user_categorizations".* FROM "user_categorizations" WHERE
"user_categorizations"."category_id" = 3 AND "user_categorizations"."user_id" = 5
ORDER BY "user_categorizations"."[:user_id, :category_id]" ASC LIMIT 1
如果我self.primary_key = [:user_id, :category_id]
从模型中删除,它可以正确检索记录但无法保存,因为它不知道在 WHERE 子句中使用什么:
SQLite3::SQLException: no such column: user_categorizations.:
UPDATE "user_categorizations" SET "score" = ?
WHERE "user_categorizations"."" IS NULL
有没有人见过这个?