Note that there are some explanatory texts on larger screens.

plurals
  1. POMongoid namespaced models and inheritance
    primarykey
    data
    text
    <p>I'm trying the use namespaced models with Mongoid and can't seem to get it to work.</p> <p>I have the following models: Achievement, Flag, FlagCaptured</p> <p>Achievment is the base class for FlagCaptured.</p> <p>app/models/achievement.rb</p> <pre><code>class Achievement include Mongoid::Document include Mongoid::Timestamps::Created belongs_to :team end </code></pre> <p>app/models/flag.rb</p> <pre><code>class Flag include Mongoid::Document field :name, :type =&gt; String field :key, :type =&gt; String, :default =&gt; SecureRandom.base64 field :score, :type =&gt; Integer belongs_to :achievement, :class_name =&gt; "Achievements::FlagCaptured" validates :name, :presence =&gt; true, :uniqueness =&gt; true validates :key, :presence =&gt; true, :uniqueness =&gt; true validates :score, :presence =&gt; true, :numericality =&gt; { :only_integer =&gt; true } def captured? !achievement_id.nil? end end </code></pre> <p>app/models/achievements/flag_captured.rb</p> <pre><code>module Achievements class FlagCaptured &lt; Achievement has_one :flag, :foreign_key =&gt; :achievement_id, :autosave =&gt; true def score self.flag.score end end end </code></pre> <p>I create the FlagCaptured achievement in the console like so:</p> <pre><code>Achievements::FlagCaptured.create(:flag =&gt; Flag.first, :team =&gt; Team.first) </code></pre> <p>Now the achievement will be created and I can get it with:</p> <pre><code>Achievements::FlagCaptured.first </code></pre> <p>However, neither side of the relation is set.</p> <p>So</p> <pre><code>Achievements::FlagCaptured.first.flag </code></pre> <p>is nil</p> <p>and</p> <pre><code>Achievements::FlagCaptured.first.flag_id </code></pre> <p>gives a NoMethodError.</p> <p>Further both:</p> <pre><code>Flag.first.achievement Flag.first.achievement_id </code></pre> <p>are nil.</p> <p>What is going on here? I've tried everything I can think of (setting the foreign keys, specifying the class names, specifying the inverse relation) and nothing works. :(</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload