Как мне установить reference_one в Mongoid? - PullRequest
2 голосов
/ 16 декабря 2010

Учитывая следующие данные, команда не работает в 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 голосов
/ 10 августа 2011

Я думаю, вы должны использовать belongs_to и has_many (или has_one) вместо references_one и referenced_in. Смотри http://mongoid.org/docs/relations/referenced/1-n.html

...