当我尝试使用此代码时,我在“self.save ...”行收到 IllegalContextError。你能告诉我我做错了什么吗?
我只会在 Player 上调用 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)