我希望有一个与两个用户相关联的ECardMatch,并且能够通过像@user.ecard_matches.new
之类的关联来创建......
我可以做这样的事情:
user = User.new
user.ecard_matches
这将返回[]
空数组
但我做不到
em = EcardMatch.new
user.ecard_matches << em
错误:
NoMethodError: You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.include?
或
user.ecard_matches.new
错误:
NoMethodError: undefined method `new' for []:Array
我的模型中的关联可能有问题。我是rails和mongodb的新手,所以也许这种用法是不好的做法......
用户类:
class User
include MongoMapper::Document
attr_accessor :password
key :name, String
key :perika, Integer
key :digest_password, String
many :ecard_matches
end
EcardMatch类:
class EcardMatch
include MongoMapper::Document
key :wager, Integer
key :turn, Integer
key :first_user_score, Integer
key :second_user_score, Integer
belongs_to :first_user, class_name: "User"
belongs_to :second_user, class_name: "User"
end
答案 0 :(得分:0)
user = User.new
user.ecard_matches << EcardMatch.new(:prop1=> '....', :prop1=> '....', ...)
user.ecard_matches << EcardMatch.new(:prop1=> '....', :prop2=> '....', ....)
user.save
这个例子可以有用吗?