Reputation: 239017
I'm creating a multi-tenant application and am trying to figure out how to model this relationship with Mongoid. I have a Site
model which has_many :domains
, or embeds_many
, or even uses an array of strings if that will work. I want to validate that only unique domains can be associated (so two Sites
can't have the same domain). I also want to be able to find a site by a given domain.
How would I represent this using Mongoid? Also, how would I query for the Site
by a given domain?
Upvotes: 0
Views: 84
Reputation: 16730
You better go with the has_many association.
In the domain model just do and you will be good. Assuming you want unique domain names, if url just change it.
validates_uniqueness_of :name
If you embed it, you can't do that validation easily, you you need to fetch all site and domains, or keep a different collection with just the domain names to see if it exists. Same for query the site with a given domain. Because you couldn't get the domain, without knowing the site it belongs.
If you do the proper relations as
class Site
field :name
has_many :domains
end
class Domain
field :name
belongs_to :site
end
You can then do, like in ActiveRecord
some_domain.site
docs: http://mongoid.org/en/mongoid/docs/relations.html#has_many
Upvotes: 1