在尝试测试我的模型时,我试图在rails控制台中运行以下命令:
user.occasions << Occasion.first
收到此错误:
irb(main):013:0> user.occasions << Occasion.first
Occasion Load (0.2ms) SELECT "occasions".* FROM "occasions" LIMIT 1
(0.0ms) begin transaction
(0.0ms) rollback transaction
ActiveRecord::AssociationTypeMismatch: Occasion(#70119208170580) expected, got NilClass(#70119200119960)`
以下是我的模型类:
class User < ActiveRecord::Base
has_many :occasions
rolify
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
attr_accessible :name, :email, :password, :password_confirmation, :remember_me, :id
end
class Occasion < ActiveRecord::Base
attr_accessible :date, :name
belongs_to :user
end
如何让我的代码片段起作用?
答案 0 :(得分:4)
看起来好像是:
Occasion
记录添加到此User
- 并且尚未创建Occasion
条记录,或Occasion
记录添加到此User
,并且该记录已属于另一个User
。你可以在控制台试试并发布结果吗?
foo = Occasion.first
Occasion.first.inspect