NOTE: This will only work with postgresql - need different code for
mysql etc.
This example mods the integer field :counter as a serial starting at 1
and incrementing by 3.
For some reason not known to me I haven't been able to figure out the
way to say
execute "ALTER TABLE simple_models ALTER COLUMN counter SET DEFAULT
nextval('simple_models_counter_seq')"
in the migration file.
db/migrations/NNNNN_create_simple_models.rb
-------------
class CreateSimpleModels < ActiveRecord::Migration
def self.up
create_table :simple_models do |t|
t.string :name
t.integer :counter
t.timestamps
end
execute "CREATE SEQUENCE simple_models_counter_seq OWNED BY
simple_models.counter INCREMENT BY 3 START WITH 1"
end
def self.down
drop_table :simple_models
end
end
-------------
models/simple_model.rb
-------------
class SimpleModel < ActiveRecord::Base
validates_uniqueness_of :name
before_create :increment_counter
private
def increment_counter
value = ActiveRecord::Migration::execute "SELECT nextval
('simple_models_counter_seq')"
self.counter = value[0]["nextval"]
end
end
-------------
On Sep 7, 6:29 am, adrianopol <[email protected]> wrote:
> There is a table:
>
> execute (<<-SQL)
> CREATE TABLE "tasks" (
> "id" serial primary key,
> "number" serial,
> "version" integer DEFAULT 0 NOT NULL,
> "latest_version" boolean DEFAULT 't' NOT NULL,
> "hidden" boolean DEFAULT 'f' NOT NULL,
> "type" character varying (1) NOT NULL,
> "created_at" timestamp
> );
> SQL
>
> I need the number field to be serial, i.e. to be automatically filled
> when mising it in the hash for create method. I had to write sql-code,
> because for postgresql adapter cannot create serial-fields. But in
> this case when trying to add
>
> task = Task.create ( :type => "c")
>
> error is raised:
>
> PGError: ERROR: null value in column "number" violates not-null
> constraint
> : INSERT INTO "tasks" ( "number", "latest_version", "type", "version",
> "hidden", "created_at") VALUES (NULL, 't', E'c ', 0,' f ', '2009-09-07
> 08:43:13.534476 ') RETURNING "id"
>
> i.e. NULL is specified for number field. Can I exclude the number
> field from the list for INSERT or maybe there is any other more
> correct way to cope with it?
>
> Thanks.
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "Ruby
on Rails: Talk" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---