MongoMapper + Rails 协会不起作用

发布于 2025-01-07 06:51:05 字数 1203 浏览 1 评论 0原文

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

I want to have an ECardMatch that is associated to two Users, and to be able to create through associations like this @user.ecard_matches.new etc...

I am able to do something like this:

user = User.new
user.ecard_matches

This returns an [] empty array

But I can't do

em = EcardMatch.new
user.ecard_matches << em

Error:

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?

or
user.ecard_matches.new

Error:

NoMethodError: undefined method `new' for []:Array

Maybe something is wrong with my associations in the model. I am new to rails and mongodb so maybe this kind of usage is bad practice...

User class:

class User
  include MongoMapper::Document

  attr_accessor :password

  key :name, String
  key :perika, Integer
  key :digest_password, String

  many :ecard_matches
end

EcardMatch class:

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

Spring初心 2025-01-14 06:51:05
user = User.new 
user.ecard_matches << EcardMatch.new(:prop1=> '....', :prop1=> '....', ...)
user.ecard_matches << EcardMatch.new(:prop1=> '....', :prop2=> '....', ....)
user.save

这个例子有帮助吗?

user = User.new 
user.ecard_matches << EcardMatch.new(:prop1=> '....', :prop1=> '....', ...)
user.ecard_matches << EcardMatch.new(:prop1=> '....', :prop2=> '....', ....)
user.save

Could this example be helpful ?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文