引用嵌入资源 mongo mongoid ruby rails

referencing embedded resources mongo mongoid ruby rails

ruby 2.50 rails 5.1.4 gem 'mongoid' gem 'mongoid_paranoia' gem 'mongoid-tree' gem 'mongoid-autoinc' gem 'mongoid-userstamps'

我在使用嵌入式资源时遇到问题。

我有一个 Account 模型。

class Account
  store_in collection: 'accounts'

  has_many :email_routes, dependent: :destroy
  embeds_many :labels, as: :labelable

  etc..
end

如您所见,每个帐户都有很多标签。

class Label
  embedded_in :labelable, polymorphic: true
  belongs_to :email_routes

  field :text, type: String
  field :color, type: String
end

可用标签在帐户级别指定...

我有一个 EmailRoute,我想给它应用一些标签..

class EmailRoute
  belongs_to :account

  field :email_address, type: String
  has_many :labels, as: :labelable, dependent: :nullify

  # field :labels, type: Array, default: []
end

email_routes_controller中,我有一个简单的更新动作..

def update
  selected_labels = params[:labels]

  @email_route.update_attributes!(labels: selected_labels)

  render json: @email_route
end

params[:labels] 包含 Label 个对象的数组。当我修补到控制器时,我得到以下 error/message.

Referencing a(n) Label document from the EmailRoute document via a relational association is not allowed since the Label is embedded.

summary:
In order to properly access a(n) Label from EmailRoute the reference would need to go through the root document of Label. In a simple case this would require Mongoid to store an extra foreign key for the root, in more complex cases where Label is multiple levels deep a key would need to be stored for each parent up the hierarchy.

resolution:
Consider not embedding Label, or do the key storage and access in a custom manner in the application code.):"

有什么办法可以解决这个问题吗?我知道有很多关于嵌入式的文章,但 none 似乎非常适合这种特殊情况。非常感谢任何帮助,因为我不想丢失标签数据并且需要在帐户级别指定它们。

谢谢!

edit 这样的事情是唯一的解决方案吗? https://www.cookieshq.co.uk/posts/switching-relationships-with-mongoid

edit 2 ... 在从 rails 控制台调用 @account.email_routes[0].labels 时,我已经设法做到了这一点。选择器内嵌套数组中的字符串是我要添加的标签。但是,当我渲染 :json @account.email_route 时,标签数组返回为空。如何使用选择器中的信息?

#<Mongoid::Criteria

selector: {"_id"=>{"$in"=>["Critical Test updates", "Chill", "New", >"Make", "Cool", "1", "2", "3"]}} options: {} class: Label embedded: true>

EmailRoute 模型中的这个 getter 可以解决问题

def labels
    account.labels.where(:_id.in => self[:labels])
end