开发者

Mongoid namespaced models and inheritance

开发者 https://www.devze.com 2023-04-07 11:54 出处:网络
I\'m trying the use namespaced models with Mongoid and can\'t seem to get it to work. I have the following models: Achievement, Flag, FlagCaptured

I'm trying the use namespaced models with Mongoid and can't seem to get it to work.

I have the following models: Achievement, Flag, FlagCaptured

Achievment is the base class for FlagCaptured.

app/models/achievement.rb

class Achievement
    include Mongoid::Document
    include Mongoid::Timestamps::Created

    belongs_to :team
end

app/models/flag.rb

class Flag
    include Mongoid::Document

    field :name,  :type => String
    field :key,   :type => String, :default => SecureRandom.base64
    field :score, :type => Integer

    belongs_to :achievement, :class_name => "Achievements::FlagCaptured"

    validates :name,  :presence => true, :uniqueness => true
    validates :key,   :presence => true, :uniqueness => true
    validates :score, :presence => true, :numericality => { :only_integer => true }

    def captured?
        !achievement_id.nil?
    end
end

app/models/achievements/flag_captured.rb

module Achievements
    class FlagCaptured < Achievement
        has_one :flag, :foreign_key => :achievement_id, :autosave => true

        def score
            self.flag.score
        end
    end
end

I create the FlagCaptured achievement in the console like so:

Achievements::FlagCaptured.create(:flag => Flag.first, :team => Team.first)开发者_运维百科

Now the achievement will be created and I can get it with:

Achievements::FlagCaptured.first

However, neither side of the relation is set.

So

Achievements::FlagCaptured.first.flag

is nil

and

Achievements::FlagCaptured.first.flag_id

gives a NoMethodError.

Further both:

Flag.first.achievement

Flag.first.achievement_id

are nil.

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. :(


Turns out that I needed to add

:autosave => true

to the relation in the FlagCaptured model and define the right foreign key and everything is working fine now.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号