【问题标题】:MongoID, embedding a document in multiple documentsMongoID,将一个文档嵌入到多个文档中
【发布时间】:2023-03-07 16:35:02
【问题描述】:

我有一个像下面这样的模型地址

class Address
  include Mongoid::Document

  field :line1
  field :city
  # more fields like this

  embedded_in :user, :inverse_of => :permanent_address
  embedded_in :user, :inverse_of => :current_address
  embedded_in :college, :inverse_of => :address
end

有嵌入地址的模型学院和用户

class College
  include Mongoid::Document

  references_many :users
  embeds_one :address

  # some fields and more code
end


class User
  include Mongoid::Document

  referenced_in :college, :inverse_of => :users  

  embeds_one :permanent_address, :class_name => "Address"
  embeds_one :current_address, :class_name => "Address"

  # fields and more code
end

我在上面的设置中遇到了一些问题。我使用单一表格来询问当前和永久地址以及更多信息,但只有 current_address 被保存,而且我在永久地址中填充的数据也是如此。

Parameters: 
  {"utf8"=>"✓",
   "authenticity_token"=>"KdOLvzmKyX341SSTc1SoUG6QIP9NplbAwkQkcx8cgdk=", 
   "user"=> {
     "personal_info_attributes"=>{...},
     "nick_names_attributes"=>{...}, 
     "current_address_attributes"=>{
        "line1"=>"", 
        "area"=>"", 
        "country"=>"USA", 
        "postal_code"=>"sd", 
        "city"=>"", 
        "state"=>"", 
        "landmark"=>"", 
        "id"=>"4d891397932ecf36a4000064"
     }, 
     "permanent_address_attributes"=>{
       "line1"=>"", 
       "area"=>"asd", 
       "country"=>"india", 
       "postal_code"=>"", 
       "city"=>"", 
       "state"=>"", 
       "landmark"=>""
     }, 
     "commit"=>"Submit", "id"=>"4d8903d6932ecf32cf000001"}
MONGODB alma_connect['users'].find({:_id=>BSON::ObjectId('4d8903d6932ecf32cf000001')})
MONGODB alma_connect['users'].update({"_id"=>BSON::ObjectId('4d8903d6932ecf32cf000001')}, 
  {"$set"=>{
    "current_address"=>{
      "line1"=>"", 
      "area"=>"asd", 
      "country"=>"india", 
      "postal_code"=>"", 
      "city"=>"", 
      "state"=>"", 
      "landmark"=>"", 
      "_id"=>BSON::ObjectId('4d8916e9932ecf381f000005')}}})

我不确定这是我做错了什么还是有其他问题。我正在使用 Rails 3.0.4 和 MongoID 2.0.0.rc.7

更新:

我升级到 mongoid 2.0.1 并更改了我的用户以在地址中包含选项的反转。

class User
  include Mongoid::Document

  referenced_in :college, :inverse_of => :users  

  embeds_one :permanent_address, :class_name => "Address", :inverse_of => :permanent_address
  embeds_one :current_address, :class_name => "Address", :inverse_of => :current_address

  # fields and more code
end

我知道名称的倒数没有意义,但这里的重点只是让它们不同,或者如果您在嵌入式类中有好的关系名称(如:current_user,:permanent_user),您应该使用的倒数。

【问题讨论】:

    标签: ruby-on-rails-3 mongoid


    【解决方案1】:

    我觉得不错。我有一个类似的设置,它按预期工作。

    【讨论】:

    • 我在上面遇到了一些问题。我使用一个表单来获取 current_address 和 Permanent_address,但只保存当前地址。
    猜你喜欢
    • 1970-01-01
    • 2016-10-11
    • 2011-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多