在尝试保存数据映射模型时,如何解决IllegalContextError?

时间:2013-02-01 07:05:10

标签: ruby initialization datamapper

当我尝试这段代码时,我在“self.save ...”行获得了一个IllegalContextError。你能告诉我我做错了什么吗?

我只是在播放器上调用create方法而不会搞乱初始化,但我希望在初始化过程中创建一个相关的周对象。

require 'data_mapper'

DataMapper::setup(:default, "sqlite3://#{Dir.pwd}/prod.db")

class Player

    include DataMapper::Resource
    property :name, String, :key => true
    property :sport, String

    has n, :weeks

    def initialize(name, sport, week)
        self.save(:name => name, :sport => sport)
        self.weeks.create(:id => "#{name}#{week}", :score => 0)
    end

end

class Week

    include DataMapper::Resource
    property :id, String, :key => true
    property :week, Integer
    property :score, Integer

    belongs_to :player

end

DataMapper.finalize.auto_migrate!

Player.new("jack", "golf", 5)

1 个答案:

答案 0 :(得分:0)

我知道这可能不是最好的方法,所以在你拍摄我的方法之前,请提供更好的解决方案。我可能会接受你的答案:)

似乎IllegalContextError源自data_mapper验证器。

验证器上的data_mapper文档没有为新手提供太多信息来理解上下文和验证器。

这是我的hacky解决方法。我使用bang运算符(!)覆盖验证器。解决方案如下。

require 'data_mapper'

DataMapper::setup(:default, "sqlite3://#{Dir.pwd}/prod.db")

class Player

    include DataMapper::Resource
    property :name, String, :key => true
    property :sport, String

    has n, :weeks

    def initialize(name, sport, week)
        self[:name] = name
        self[:sport] = sport
        self[:week] = week
        self.save!
        self.weeks.create(:id => "#{name}#{week}", :score => 0)
    end

end

class Week

    include DataMapper::Resource
    property :id, String, :key => true
    property :week, Integer
    property :score, Integer

    belongs_to :player

end

DataMapper.finalize.auto_migrate!

Player.new("jack", "golf", 5)