Mongoid字段没有被持久化

时间:2011-09-08 21:13:17

标签: ruby-on-rails mongoid

所以我有一个非常简单的mongoid类:

class Offer
  include Mongoid::Document

  field :date, type: DateTime
  field :accepted, type: Boolean

  scope :accepted, where(accepted: true)
  scope :denied, where(accepted: false)

  belongs_to :from, class_name: 'User', inverse_of: :from_offers
  belongs_to :to, class_name: 'User', inverse_of: :to_offers
  belongs_to :update 
end

但是,创建后,可以更新其中的任何字段。如果我执行了offer.accepted = true然后是offer.save!之类的操作,则不会引发任何错误,但是一旦操作完成并刷新页面或w / e,则更改将被还原。我真的不知道如何继续。有什么帮助吗?

更新:我的更新类不应该有offer_id字段吗?

=> #<Update _id: 4e6933836066250375000033, _type: nil, updated_at: 2011-09-08 21:28:44 UTC, type: "offer", unread: false, topic_id: nil, post_id: nil, user_id: BSON::ObjectId('4e692ad3606625123b000001'), profile_id: nil, commenter_id: BSON::ObjectId('4e692b0b606625037500002a')>

UPDATE2:我认为这可能是has_one的错误。我已经恢复了将更新的id存储在字符串字段而不是has_one连接中,一切似乎都没问题。

1 个答案:

答案 0 :(得分:0)

这也被报告为GitHub issue

我无法使用Mongoid 2.2.0或2.2.0-stable分支重现问题(截至d6ace09c)。

此代码:

class Offer
  include Mongoid::Document

  field :date, type: DateTime
  field :accepted, type: Boolean

  scope :accepted, where(accepted: true)
  scope :denied, where(accepted: false)

  belongs_to :from, class_name: 'User', inverse_of: :from_offers
  belongs_to :to,   class_name: 'User', inverse_of: :to_offers
end

class User
  include Mongoid::Document

  has_many :from_offers,  :class_name => 'Offer', :inverse_of => :from
  has_many :to_offers,    :class_name => 'Offer', :inverse_of => :to
end

User.delete_all
Offer.delete_all

user1 = User.create
user2 = User.create
user3 = User.create
puts "user1 ID = #{user1.id}"
puts "user2 ID = #{user2.id}"
puts "user3 ID = #{user3.id}"

Offer.create(
  :date     => Date.today,
  :accepted => false,
  :from     => user1,
  :to       => user2,
)

ap Offer.first.attributes
Offer.first.update_attributes :accepted => true, :to => user3
ap Offer.first.attributes

生成此输出,显示offer已成功更新:

user1 ID = 4e696a052b58af5dce000001
user2 ID = 4e696a052b58af5dce000002
user3 ID = 4e696a052b58af5dce000003
{
         "_id" => BSON::ObjectId('4e696a052b58af5dce000004'),
        "date" => 2011-09-08 04:00:00 UTC,
    "accepted" => false,
     "from_id" => BSON::ObjectId('4e696a052b58af5dce000001'),
       "to_id" => BSON::ObjectId('4e696a052b58af5dce000002')
}
{
         "_id" => BSON::ObjectId('4e696a052b58af5dce000004'),
        "date" => 2011-09-08 04:00:00 UTC,
    "accepted" => true,
     "from_id" => BSON::ObjectId('4e696a052b58af5dce000001'),
       "to_id" => BSON::ObjectId('4e696a052b58af5dce000003')
}