【发布时间】:2013-09-19 22:27:50
【问题描述】:
我有一个相当简单的查询来返回多对多关系中的第一条记录,或者如果它不存在则创建一条记录。
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
有人见过吗?
【问题讨论】:
-
是的,但是看看它是怎么说列名是确切的字符串
[:user_id, :category_id]?这可能是由于self.primary_key设置所致。 -
你为什么要以你现在的方式显式设置主键? Rails 会自动推断相关模型的主键。您是否要创建复合主键?
-
啊,所以当我删除它时它可以正确检索它,但是当我尝试更改变量并保存时,它会尝试在没有主键的情况下进行更新:
SQLite3::SQLException: no such column: user_categorizations.: UPDATE "user_categorizations" SET "score" = ? WHERE "user_categorizations"."" IS NULL。
标签: sql ruby-on-rails ruby activerecord ruby-on-rails-4