Rails 不会使用序列作为主键?

发布于 2024-10-06 12:23:57 字数 374 浏览 2 评论 0原文

由于某种原因,我在 Rails 应用程序中使用的预先存在的 Postgres 架构没有为表的主键设置默认序列,因此每次想要创建新行时都需要查询它。

我的模型中有 set_sequence_name "seq_people_id" ,但是每当我调用 Person.new 时,Postgres 都会向我抱怨,因为 Rails 正在执行没有 ID 的插入查询(标记为架构中的 NOT NULL)。

如何告诉 Rails 在创建新记录时始终使用该序列?

  • Postgres 8.1.4
  • ActiveRecord 3.0.3
  • Rails 2.3.10

For one reason or another the pre-existing Postgres schema I'm using with my Rails app doesn't have a default sequence set for a table's primary key, so I am required to query for it every time I want to create a new row.

I have set_sequence_name "seq_people_id" in my model, but whenever I call Person.new Postgres complains to me because Rails is executing the insert query without the ID (which is marked as NOT NULL in the schema).

How do I tell Rails to always use the sequence when creating new records?

  • Postgres 8.1.4
  • ActiveRecord 3.0.3
  • Rails 2.3.10

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

成熟的代价 2024-10-13 12:23:57

这是我运行 psql 和 \d foo 时得到的结果:

                                 Table "public.foo"


 Column |   Type        |              Modifiers                       
--------+---------------+------------------------------------------------------
  id    | integer       | not null default nextval('foo_id_seq'::regclass)
(etc.)

我会检查以下内容:

  • 验证实际序列名称与您引用的名称相同(people_id_seq 与 seq_people_id)
  • 验证表的默认值与我上面的类似
  • (只是检查)主键的字段是否名为“id”?
  • 您是使用迁移还是手动创建表?如果是后者,请尝试创建一个带有迁移的表,并指定与人员表中相同的字段。它工作正常吗?比较表格。

Here's what I get when I run psql and \d foo:

                                 Table "public.foo"


 Column |   Type        |              Modifiers                       
--------+---------------+------------------------------------------------------
  id    | integer       | not null default nextval('foo_id_seq'::regclass)
(etc.)

I'd check the following:

  • Verify the actual sequence name is the same as what you reference (people_id_seq vs. seq_people_id)
  • Verify the table's default is similar to what I have above
  • (just checking) is the primary key's field named "id" ?
  • Did you create the table using a migration or by hand? If the latter, try creating a table with a migration, specifying the same fields as in your people table. Does it work properly? Compare the tables.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文