如何在Mongoid中设置references_one?

时间:2010-12-16 01:46:18

标签: ruby-on-rails mongoid

鉴于以下数据,该命令在Mongoid中不起作用...我退出命令行并且它没有设置或显示。 User.plan仍等于零。我不知道它如何在网页中工作而不仅仅是命令行。我曾经和Rails合作过,但由于某些原因,Mongoid正在逃避我。

计划课程:

class Plan
  include Mongoid::Document
  field :active, :type => Boolean, :default => true
  field :cost, :type => Integer
  field :emails, :type => Integer
  field :active_surveys, :type => Integer
  field :name, :type => String

  scope :active, where(:active => true)

  scope :default, asc(:cost)

  referenced_in :user
end

用户类:

class User
  include Mongoid::Document
  # Include default devise modules. Others available are:
  # :token_authenticatable, :confirmable, :lockable and :timeoutable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  field :name, :type => String
  field :admin, :type => Boolean, :default => false
  validates_presence_of :name, :email
  validates_uniqueness_of :name, :email, :case_sensitive => false
  attr_accessible :name, :email, :password, :password_confirmation, :remember_me

  references_one :plan

  delegate :emails,
           :active_surveys,
           :to => :plan,
           :prefix => true
end

命令行输出:

ruby-1.9.2-p0 > p = Plan.where(:name => "Mega").first
 => #<Plan _id: 4d09434aec286527fe000009, active: true, cost: 15, emails: 1000, active_surveys: 100, name: "Mega", user_id: nil> 
ruby-1.9.2-p0 > u = User.first
 => #<User _id: 4d042734ec28651f2a000002, email: "me@example.com", encrypted_password: "-", password_salt: "-", remember_token: nil, remember_created_at: nil, reset_password_token: nil, sign_in_count: 1, current_sign_in_at: 2010-12-13 03:36:32 UTC, last_sign_in_at: 2010-12-13 03:36:32 UTC, current_sign_in_ip: "127.0.0.1", last_sign_in_ip: "127.0.0.1", name: "First Last", admin: true> 
ruby-1.9.2-p0 > u.plan
 => nil 
ruby-1.9.2-p0 > u.errors
 => {} 
ruby-1.9.2-p0 > u.plan = p
 => #<Plan _id: 4d09434aec286527fe000009, active: true, cost: 15, emails: 1000, active_surveys: 100, name: "Mega", user_id: BSON::ObjectId('4d042734ec28651f2a000002')> 
ruby-1.9.2-p0 > u.save
 => true 
ruby-1.9.2-p0 > u.errors
 => {} 

1 个答案:

答案 0 :(得分:0)

我认为您应该使用belongs_tohas_many(或has_one)而不是references_onereferenced_in。见http://mongoid.org/docs/relations/referenced/1-n.html