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/