model won't create because can't find ID in Rails
I have two models.
class User
has_one :spec, :dependent => :destroy
# returns true for a duplicat record
def duplicate?
user = User.find_by_email(email)
self.id = user.id unless user.nil?
not user.nil?
end
class Spec
belongs_to :user
validate_uniqueness_of :user_id
Controller
if @user.duplicate? || @user.save
@user.create_spec(:birthdate => params[:user][:deliver_on])
end
This produces the following error:
ActiveRecord::StatementInvalid in BoardController#new
Mysql::Error: Column 'user_id' cannot be null: INSERT INTO `specs` (`created_at`, `birthdate`, `updated_at`, `avatar`, `gender`, `user_id`, `last_name`, `first_name`, `picture`) VALUES('2011-03-09 05:43:46', NULL, '2011-03-09 05:43:46', '../images/default_avatar.jpg', NULL, NULL, '', '', NULL)
However if I do this:
@user.create_spec(:user_i开发者_StackOverflowd => @user, :birthdate => params[:user][:deliver_on])
it works!
I thought doing @user.create_spec would supplies the user_id automatically.
Anyway to make this work the way its supposed to? I appreciate any feedback. Thank
I think you are having the wrong approach. According to you,
class User has_one :spec end
But you are creating another spec for duplicate user. So I suggest following link.
http://www.hackerdude.com/2005/11/28/one-to-one-relationships-with-rails/
精彩评论