【问题标题】:MongoMapper + Rails associations don't workMongoMapper + Rails 关联不起作用
【发布时间】:2012-02-20 22:52:07
【问题描述】:

我想要一个与两个用户相关联的 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

【问题讨论】:

  • 你能提供NoMethodError的回溯吗? &lt;&lt; 语法应该可以工作,但你想要 user.ecard_matches.build 而不是 user.ecard_matches.new

标签: ruby-on-rails mongodb mongomapper


【解决方案1】:
user = User.new 
user.ecard_matches << EcardMatch.new(:prop1=> '....', :prop1=> '....', ...)
user.ecard_matches << EcardMatch.new(:prop1=> '....', :prop2=> '....', ....)
user.save

这个例子有帮助吗?

【讨论】:

  • 恐怕不是 NoMethodError: 你有一个 nil 对象,你没想到!您可能期望有一个 Array 的实例。评估 nil.include 时发生错误?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多