我难住了。我不断收到Called id for nil
错误假设我有以下模型:
class User < ActiveRecord::Base
self.primary_key = 'name'
attr_accessible :name
has_many :projects, :through => :user_projects
has_many :user_projects
end
class UserProject < ActiveRecord::Base
belongs_to :user
belongs_to :project
after_save do |r|
puts r.user.id #<<<<<error here!
end
end
class Project < ActiveRecord::Base
attr_accessible :name#, :body
has_many :user_projects
has_many :users, :through=> :user_projects
# attr_accessible :title, :body
end
以及以下迁移:
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :name
t.timestamps
end
end
end
class CreateProjects < ActiveRecord::Migration
def change
create_table :projects do |t|
t.string :name
t.timestamps
end
end
end
class CreateUserProjects < ActiveRecord::Migration
def change
create_table :user_projects do |t|
t.references :user
t.references :project
t.timestamps
end
end
end
运行类似:
@project = Factory.create(:project)
@user = Factory.create(:user)
@user.projects << @project
我会得到这个:
RuntimeError: Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id
为什么 after_save 回调中断,我该怎么做才能修复它?似乎我根本无法从回调中引用关联的用户对象。但是,如果我删除
self.primary_key = 'name'
从用户模型,一切正常。我错过了一些东西,但我不知道是什么。
提前致谢!顺便说一句,我在 Rails 3.2.6 上。