没有主键的 ActiveRecord 模型 [英] ActiveRecord model without primary key
问题描述
我有一个没有主键的 ActiveRecord 模型 GPA
:
I have a ActiveRecord model GPA
that doesn't have a primary key:
class GPA < ActiveRecord::Base
end
当我尝试调用 GPA.first.to_json
时,我得到 TypeError: false is not a symbol
.我猜这是由于 ActiveRecord 试图查找主键.在没有主键的情况下实现模型的正确方法是什么?
When I try to call GPA.first.to_json
I get TypeError: false is not a symbol
. I'm guessing that this is due to ActiveRecord trying to lookup the primary key. What is the correct way to implement a model without a primary key?
推荐答案
通常有一些列或列组合在一起形成主键.当您说您的表没有主键时,您的意思是它没有 id
字段吗?
Normally there is either some column or combination of columns which together do form a primary key. When you say your table doesn't have a primary key do you mean it doesn't have an id
field?
是否还有另一列是唯一/自然键?如果是这样,您可以这样做:
Is there another column that is a unique/natural key? If so you can do:
class GPA < ActiveRecord::Base
set_primary_key :strm # eg column strm is a unique/natural key
end
您还可以将复合键与 复合键 gem 一起使用,如下所示:
You can also use composite keys with the composite keys gem, as follows:
class GPA < ActiveRecord::Base
set_primary_keys :student_id, :strm
end
这篇关于没有主键的 ActiveRecord 模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!