问题
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
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
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>
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?
回答1:
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
回答2:
Exactly it's currently a class method :
http://api.rubyonrails.org/classes/ActiveRecord/AttributeMethods/PrimaryKey/ClassMethods.html#method-i-primary_key-3D
Don't forget the adequate migration :
def up
create_table :books, {id: false, primary_key: :key_id} do |t|
t.timestamps
etc.
end
execute <<-SQL
ALTER TABLE books
ADD PRIMARY KEY (key_id)
SQL
end
def down
drop_table :books
end
If you want to use this new primary key in your generated routes (routes.rb) :
resources :books, only: [:show, :edit, :update], param: :key_id
Hope it helps !
Take care
回答3:
Weird. As per documentation I would have expected
class Index < ActiveRecord::Base
set_primary_key "name"
end
to work. The only difference I can see is "name" string vs your :name symbol which shouldn't make any difference.
Update
Actually, bang up the top of that link is a deprecated message (sorry). Apparently it's now a class method so that explains the need for self.set_primary_key. Doh!
来源:https://stackoverflow.com/questions/20386636/set-primary-key-error-in-rails