Reputation: 289
I have 2 models: User and UserLvl.
class User < ActiveRecord::Base
has_one :user_lvl, primary_key: 'user_lvl_id', foreign_key: 'id'
end
class UserLvl < ActiveRecord::Base
belongs_to :user
end
Controller action
def change_lvl
@user.user_lvl = UserLvl.first
@user.save
end
UserLvl.first
is returned fine,with id
and all but it failes at the first line with : "Column 'id' cannot be null"
why is this happening?
EDIT:
schema.rb
create_table "users", force: true do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.integer "user_lvl_id"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "user_lvls", force: true do |t|
[omited some information]
t.datetime "created_at"
t.datetime "updated_at"
end
Upvotes: 1
Views: 46
Reputation: 20125
You probably want to use a belongs_to
association rather than a has_one
, like this:
class User < ActiveRecord::Base
belongs_to :user_lvl
end
Your foreign key is placed in the users
table, which makes User
the associated model, that belongs to the UserLvl
.
Upvotes: 2