bukk530
bukk530

Reputation: 1897

RoR - Mongoid foreign key inside an hash

Let's say I have two models, in this example a site and a theme, and I want to make a site belong to a theme, but referencing it with a key inside an hash.

class Site
  include Mongoid::Document

  field :preferences, type: Hash

  belongs_to :theme, foreign_key: :"preferences.theme_id"

end

As you can see the theme_id is stored inside an hash named "preferences", the problem is that with this code mongoid can't find the right theme_id. How should I deal with this situation?

Upvotes: 0

Views: 124

Answers (1)

mu is too short
mu is too short

Reputation: 434585

If you want to keep your preferences together and they're structured, you could use an embedded document instead of a plain Hash:

class Site
  include Mongoid::Document
  embeds_one :preferences, :class_name => 'Preferences'
end
class Preferences
  include Mongoid::Document
  embedded_in :site
  belongs_to :theme
end

Your preferences would still be a Hash inside the database but you'd get enough Mongoid wrapping to make the association work. If you do this, then you'd say things like:

t = site.preferences.theme

If you wanted to, you could delegate the theme call from Site instances to their embedded preferences.

Upvotes: 1

Related Questions