Custom Keys for the Mongoid Association

I need to associate two models with a simple has_many. The problem is that I do not want to use id (_id) as the primary key for the association. I still want the model to continue to use the default ObjectIds for everything else.

(runs on Rails3.1 + Mongoid)

So basically I want:

class Message ... field :message_id, :default => proc { "fail-#{Time.now.to_f.to_s}" } ... has_many :message_reports, primary_key: :message_id, foreign_key: :message_id ... end class MessageReport ... field :message_id, :default => proc { "fail-#{Time.now.to_f.to_s}" } ... has_many :message, primary_key: :message_id, foreign_key: :message_id ... end 

This will only work for ActiveRecord. Mongoid does not support the primary_key parameter.

So, how do I get the same results for Mongoid collections?

Before saying: do not do this ...

The reason I really need kay in this field, and not the correct identifier, is because these are messages ... and message_ids are the unique identifiers returned by the API that I call to send the message. Later, the same identifier is received in callbacks on the other hand.

I could just make queries and insert them into a method to find the โ€œrelatedโ€ reports from the message and vice versa ... I would prefer that they be actual associations, if possible.

I could make the process of receiving the report search and match objects for the association ... but I would prefer not to assign this responsibility to it when it is partly superfluous, and it has nothing to do with this data, other than checking and saving.

In short: I would prefer an association :)

+6
source share
1 answer

This feature does not exist on Mongoid actually even on Master, and it is not planned in Mongoid 3.0

Request some features. The Mongolian community is really open to add a new feature if this is a good idea. This is a good idea for me.

+1
source

Source: https://habr.com/ru/post/905910/


All Articles