Mongoid:关系总是将foreign_key值设为nil

时间:2013-08-07 02:58:38

标签: ruby-on-rails ruby-on-rails-3 mongodb mongoid

我是MongoDB的新手,对Rails来说有些新手。我几乎完全在JavaEE工作,并试图分支出来。我发现了一个需要解决的问题:我的朋友想在线管理他们的D& D字符,但不喜欢任何当前的工具。听起来像一个相对简单的应用程序。

我已经添加了登录设计,并决定使用Mongoid gem为MongoDB提供一个镜头。经过一些阅读和一些教程后,我已经生成了我的应用程序,并且可以添加字符并登录/注册。因此我的问题是:当我在用户模型中定义has_many :characters的用户关系和在角色模型中定义belongs_to :user时,我在记录中保留了nil的返回值。我相信我已正确设置,任何帮助都将不胜感激。

user.rb(截断相关性)

  class User
  include Mongoid::Document
  include Mongoid::Timestamps

  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  ## Database authenticatable
  field :email,              :type => String, :default => ""
  field :encrypted_password, :type => String, :default => ""
  validates_presence_of :email, :encrypted_password

  index({ email: 1 }, { unique: true, background: true })
  field :name, type: String
  validates_presence_of :name

  attr_accessible :name, :email, :password, :password_confirmation, 
  :remember_me, :created_at, :updated_at

  ## Mappings
  has_many :characters
end

character.rb(截断相关性)

class Character
  include Mongoid::Document

  field :character_name, type: String
  field :level, type: Integer
  field :experience, type: Integer
  field :str, type: Integer
  field :con, type: Integer
  field :dex, type: Integer
  field :int, type: Integer
  field :wis, type: Integer
  field :cha, type: Integer
  field :editable, type: Boolean

  belongs_to :cduser
end

控制台输出

    1.9.3p448 :005 > Character.first
     => #<Character _id: 5201b4e76e9552c74a000002, character_name: "Test",
level: 1, experience: 1, str: 1, con: 1, dex: 1, int: 1, wis: 1, cha: 1,
editable: false, user_id: nil> 
    1.9.3p448 :006 > User.first
   => #<User _id: 5201b4aa6e95523fa4000001, created_at: 2013-08-07 02:44:58 UTC,
updated_at: 2013-08-07 02:44:58 UTC, email: "test@gmail.com", encrypted_password:
"$2a$10$SKlgfRDPYkloYP/Re6ZF2evBx1PEzRsE8JVPVhvdkLe3p0bSIcjX.", 
reset_password_token: nil, reset_password_sent_at: nil, remember_created_at: nil,
sign_in_count: 1, current_sign_in_at: 2013-08-07 02:44:58 UTC, 
last_sign_in_at: 2013-08-07 02:4

4:58 UTC, current_sign_in_ip: "127.0.0.1", 
          last_sign_in_ip: "127.0.0.1", name: "Zach"> 

1 个答案:

答案 0 :(得分:1)

在你的角色模型中,它应该是belongs_to :cduser, :class_name => "User"而不是belongs_to :cduser,因为rails无法根据命名约定来识别它所属的类。