Bindu
Bindu

Reputation: 443

NoMethodError undefined method `add_index' in Rails

I have the following code in the model

class Thorserver < ActiveRecord::Base
  add_index :Thorserver, [:ip, :mode], :unique => true
end

I see this error trying to insert to the table through the views

NoMethodError (undefined method `add_index' for #<Class:0x9a680494>):
app/models/thorserver.rb:2
app/controllers/testbeds_controller.rb:147:in `addresource'

The ruby version is ruby 1.8.6, rails version is Rails 2.3.8

Upvotes: 0

Views: 865

Answers (1)

Leo Correa
Leo Correa

Reputation: 19799

add_index is not a method of ActiveRecord::Base. That should be placed in your database migration.

You can add that statement to a migration in rails and it should add the uniqueness that you are looking for.

Another way of doing it would be to use validates_uniqueness_of validation.

I believe something like this should work validates_uniqueness_of :ip, :scope => [:mode]

However, note that since that's not done at the database level it is not guaranteed to be unique 100%. I would suggest still adding the index that you have in the migration and update your db with it as well as the uniqueness validation.

Upvotes: 3

Related Questions