2012年7月31日火曜日

Point of initial data insertion on Ruby on Rails3

Environment

ruby-1.9.3-p0, rails3.2.2, postgres

Grade

normal


seeds.rb uses to insert initial data for a new application.
for example, you can insert specified id (as id => 1) on postgres table. but sequence is not changed.
therefore, if you insert a new data on admin view, you will get duplicate key error.
you should set the sequence.

seeds.rb


obj1 = TestMaster.new(:id => 1, name => "test")
obj1.save
obj2 = TestMaster.new(:id => 2, name => "test")
obj2.save
// continue until 100

In the above seeds.rb, TestMaster table register the data from 1 to 100.
but, sequence id is not changed. primary id already exists and you will get duplicate key error.
The sequence is a special value that gets nextval function.
you need to add sequence update.

set sequence_id



obj1 = TestMaster.new(:id => 1, name => "test")
obj1.save
obj2 = TestMaster.new(:id => 2, name => "test")
obj2.save
// continue until 100

// set seq
connection = ActiveRecord::Base.connection();
connection.execute("select setval('test_master_id_seq',(select max(id) from test_master))")

As above, sql execute and set sequence value.
you can get correct primary key.

Thanks for reading.
bye!

この記事がお役にたちましたらシェアをお願いします

このエントリーをはてなブックマークに追加

0 件のコメント:

コメントを投稿

Related Posts Plugin for WordPress, Blogger...