Reputation: 4964
In Rails, My Membership model migration looks like this:
class CreateMemberships < ActiveRecord::Migration
def change
create_table :memberships do |t|
t.integer :user_id
t.integer :organization_id
t.integer :membership_type_id
t.timestamps
end
end
end
and my User model migration:
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :first_name
t.string :last_name
t.string :email
t.timestamps
end
end
end
To me, these look pretty much the same. However, when I look at the tables in psql
I see this:
cd_dev=# \d memberships
Table "public.memberships"
Column | Type | Modifiers
--------------------+-----------------------------+-----------
id | integer | not null
and
cd_dev=# \d users
Table "public.users"
Column | Type | Modifiers
---------------+-----------------------------+----------------------------------------------------
id | integer | not null default nextval('users_id_seq'::regclass)
In other words, the id field of memberships
table is not automatically being assigned. In Rails console, when I attempt to create a new Membership by simply doing Membership.create(user_id: 1, organization_id: 1)
it fails saying:
ActiveRecord::StatementInvalid: PG::Error: ERROR: null value in column "id" violates not-null constraint
I could probably google a way to make the id
field work correctly on memberships
, but what I don't understand is how this happened. Is there something I should know about Rails/Postgres? I don't remember if I used rails generators or manually typed out the migration for each of these models.
Upvotes: 0
Views: 1076
Reputation: 8258
This isn't normal. Are you sure you didn't fiddle with the database manually? try
rake db:drop db:create db:migrate
Upvotes: 1