0

我难住了。我不断收到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 上。

4

2 回答 2

1

尝试在迁移中将 id 设置为 false ,如下所示:

class CreateUsers < ActiveRecord::Migration
  def change
    create_table :users, :id => false do |t|
      t.string :name
      t.timestamps
    end
  end
end
于 2012-07-21T01:57:03.370 回答
0

感谢豆鬼的启发!我想到了。t.references :project助手默认 foreign_key 为整数。我手动将其更改为正确的类型。所以现在它起作用了!

class CreateUserProjects < ActiveRecord::Migration
  def change
    create_table :user_projects do |t|
      t.string :user_id #<<<<<<< STRING!!
      t.references :project
      t.timestamps
    end
  end
end
于 2012-07-21T03:22:38.567 回答