How do I create a field using the identifier of the same row in ActiveRecord Ruby

advertisements

-----UPDATE-----

Well, seems that the problem was in last.id. When database is created works OK, but when not fails. Now the question is different: How can I create a field using the id from the same row?

--------ORIGINAL------

I'm working with active record in pure ruby (without Rails), and I'm literally getting crazy with this. This is my code

class Enviroment < ActiveRecord::Base
    #self.table_name = 'enviroments'
    self.connection.create_table(:enviroments, :force=>true) do |t|
        t.column :name, :string, :default=>'env-'+ (last.id-1).to_s
        t.column :ssh, :string, :default=>nil
    end
end

and here the error:

ActiveRecord::StatementInvalid: Could not find table 'enviroments'
from /usr/lib/ruby/gems/1.8/gems/activerecord-3.2.3/lib/active_record/connection_adapters/sqlite_adapter.rb:465:in `table_structure'

if I useself.table_name = 'enviroments' still not working. I've updated the gems and neither. I'm newbie with ruby and databases, but I can't understand this problem, I think this same code worked in the past :S


Your code to create the table (very odd to have that in the model by the way) is calling last.id, and of course to call last the table must already exist.

Because you're passing :force => true to create_table you'll actually destroy the table if it already exists.

You could probably make your code work if you stashed the value of last.id in a local variable before the call to create_table but I don't understand why you are creating tables like this.