简体   繁体   中英

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?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM