私は困惑しています。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'
User モデルから、すべてが正常に動作します。私は何かが欠けていますが、何がわかりません。
前もって感謝します!レール3.2.6のところで私。