Rails 中的 set_primary_key 错误 [英] set_primary_key error in Rails

查看:34
本文介绍了Rails 中的 set_primary_key 错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个名为 Index 的表.这是迁移:

I'm creating a table called Index. Here's the migration:

class CreateIndices < ActiveRecord::Migration
  def change
    create_table :indices, {:id => false} do |t|
      t.string :name
      t.float :returns, array: true, default: []
      t.float :navs, array: true, default: []
      t.float :sharpe

      t.timestamps
    end

    execute "ALTER TABLE indices ADD PRIMARY KEY (name);"
  end
end

一切正常.我在另一个 Stack Overflow 问题中看到,我必须在我的模型中包含 set_primary_key 命令才能使其工作,所以我在 index.rb

That all works fine. I saw in another Stack Overflow question that I have to include the set_primary_key command in my model to get it to work, so I have the following in the index.rb

class Index < ActiveRecord::Base
  set_primary_key :name

end

除了这两个文件之外,我没有对默认的 Rails 脚手架进行任何更改(该应用程序是使用 Postgres 作为默认数据库创建的).当我转到 localhost:3000/indices 时,出现以下错误

Besides these two files, I haven't changed anything from the default Rails scaffolding (the app was created with Postgres as the default database). When I go to localhost:3000/indices, I get the following error

undefined method `set_primary_key' for #<Class:0x37132e0>

如果我注释掉 set_primary_key 行,它会加载常规的空脚手架,但我认为这不会给我想要的主键功能.我做错了什么?

If I comment out the set_primary_key line it loads the regular empty scaffold, but I assume this does not give me the primary key functionality that I want. What am I doing wrong?

推荐答案

如果您使用的是 Rails 3.2 或更高版本,set_primary_key 方法已弃用,请查看 Rails 3.2 发行说明 - 第 8.1 节,它建议使用赋值方法代替 self.primary_key=,就像你说的那样在你的评论中做了

If you're using rails 3.2 or higher, the set_primary_key method was depreciated, check out the Rails 3.2 release notes - Section 8.1 and it suggests using an assignment method instead like self.primary_key=, just like you said you did in your comment

这篇关于Rails 中的 set_primary_key 错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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