Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom keys for Mongoid association

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

(This is running 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 would only work for ActiveRecord. Mongoid don't support the primary_key option.

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

Before you say: don't do that...

The reason I really really need to kay on this field and not the proper id is that these are messages... and the message_ids are unique ids returned by the API I call to send a message. Later the same id is received in callbacks from the other side.

I could just do queries and stick it in a method to find the "associated" reports from a message and vice versa... I'd rather have them be actual associations, if possible.

I could force the report-recieving process to search for and match up the objects for the association... but I'd rather not put that responsibility there when it is kind-of superfluous and it has nothing more to do with this data besides validating and saving it.

In short: I'd prefer an association :)

like image 956
Martin Westin Avatar asked Jan 13 '12 13:01

Martin Westin


1 Answers

This feature doesn't exist on Mongoid actually even on Master and it's not planned in Mongoid 3.0

Do some feature request. The Mongoid community is really open to add some new feature if it's a good idea. To me It's a good idea.

like image 142
shingara Avatar answered Oct 02 '22 17:10

shingara