ruby-on-rails - 引用嵌入式资源 mongo mongoid ruby​​ rails

标签 ruby-on-rails ruby mongodb mongoid embedded-resource

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 对象。当我修补到 Controller 时,我收到以下错误/消息。

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.):"

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

谢谢!

编辑 这样的事情会是唯一的解决方案吗? 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

关于ruby-on-rails - 引用嵌入式资源 mongo mongoid ruby​​ rails,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48755494/

相关文章:

javascript - 如何使用 mongoose 从 MongoDb 获取数据?

mongodb - 如何在 MongoDB 中创建巨大的随机文档

javascript - Rails 动态渲染部分内容

javascript - Rails form_with ajax 回调不起作用

ruby-on-rails - 在Ruby on Rails中,要扩展String类,代码应该放在哪里?

ruby - 我可以在 Windows 中将 Sass 与批处理脚本一起使用吗

mongodb - 更新 MongoDB 中的嵌入式文档

java - ruby on rails 项目中的 jar 文件放在哪里?

ruby-on-rails - digital ocean 生产服务器中的奇怪错误

ruby-on-rails - 如何检查字符串是否为有效日期