轨道4生成无效的列名 [英] Rails 4 Generating Invalid Column Names

查看:138
本文介绍了轨道4生成无效的列名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个相当简单的查询返回的第一条记录的许多一对多的关系,或创建一个,如果它不存在。

I have a fairly simple query to return the first record in a many-to-many relation or create one if it doesn't exist.

UserCategorization.where(category_id: 3, user_id: 5).first_or_create

我的模式是这样的:

My model looks like:

class UserCategorization < ActiveRecord::Base
    belongs_to :user
    belongs_to :category

    self.primary_key = [:user_id, :category_id]
end

不过它生成的SQL无效列名:

However it generates an invalid column name in the 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子句中使用:

If I remove self.primary_key = [:user_id, :category_id] from the model, it can retrieve the record correctly but cannot save because it doesn't know what to use in the WHERE clause:

SQLite3::SQLException: no such column: user_categorizations.: 

UPDATE "user_categorizations" SET "score" = ? 
WHERE "user_categorizations"."" IS NULL

有没有人见过这个?

Has anyone seen this before?

推荐答案

因此​​,它看起来像轨道4的ActiveRecord不会做复合主键非常好这么多到很多车型上面创建的问题。我固定它通过使用该扩展的ActiveRecord: http://compositekeys.rubyforge.org/

So it looks like Rails 4 ActiveRecord doesn't do composite keys very well so many-to-many models create the issues above. I fixed it by using this extension to ActiveRecord: http://compositekeys.rubyforge.org/

这篇关于轨道4生成无效的列名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆