开发者

No IDs when creating a new object in Rails with PostgreSQL as database

My setup is the following: I am using Rails 3.0.1 with a PostgreSQL 9.0 database. I have my models organized in submodules.

When I'm using the console to create a new object of any kind (c = ::Physical::Base::Contact.new) and save it, the id of the object is not automatically filled in. It is written to the database, but my object that I have just created does not take note of the ID that is generated by the sequence in PostgreSQL. My migration script for creating the table is below. I write them myself and am not using the standard rails generation feature to have more control over my tables.

Is this a standard PostgreSQL+Rails behaviour, or am I missing something by writing the migrations myself?

class Contact < ActiveRecord开发者_如何学C::Migration
  def self.up
    execute "
      create table contacts(
        id serial,
        contact_type_id integer not null check (contact_type_id > 0),
        value text not null check (length(value) > 0)
      )
    "
  end

  def self.down
    execute "
      drop table contacts;
    "
  end
end


Make sure you set a primary key on your table, I had the same problem recently, and it was very frustrating. I decided to re-create the table using migrations and noticed my old table was absent a primary key. Once I added it, things worked as expected!

You'll need something like "alter table contacts add primary key(id)" -- ActiveRecord doesn't seem to understand if there's not a primary key index on that field.

Before the primary key I would get:

ruby-1.9.2-p0 > Job.create
=> #<Job id: nil, data: nil, timestamp: nil, enqueued_at: nil, started_at: nil, completed_at: nil, status: nil, result: nil, job_queue_id: nil, job_handle: nil, uniq: nil, priority: nil, server_id: nil> 

Now that I've added the primary key, the result is:

ruby-1.9.2-p0 > Job.create
=> #<Job id: 17937, data: nil, timestamp: nil, enqueued_at: nil, started_at: nil, completed_at: nil, status: nil, result: nil, job_queue_id: nil, job_handle: nil, uniq: nil, priority: nil, server_id: nil> 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜