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' 

User モデルから、すべてが正常に動作します。私は何かが欠けていますが、何がわかりません。

前もって感謝します!レール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

Dougui のインスピレーションをありがとう! 私はそれを考え出した。ヘルパーは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 に答える