【问题标题】:How do I set up a references_one in Mongoid?如何在 Mongoid 中设置references_one?
【发布时间】:2010-12-16 01:46:17
【问题描述】:

鉴于以下数据,该命令在 Mongoid 中不起作用...我退出命令行并且它没有设置或显示。 User.plan 仍然等于 nil。而且我不知道它如何在网页中工作而不是在命令行中工作。我以前使用过 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
 => {} 

【问题讨论】:

    标签: ruby-on-rails mongoid


    【解决方案1】:

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

    【讨论】:

    • references_onehas_many 是别名。我怀疑这是否会改变任何事情。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-27
    • 1970-01-01
    相关资源
    最近更新 更多