When I try to this code, I get an IllegalContextError at the “self.save…” line. Can you tell me what I’m doing wrong?
I would just call the create method on Player without messing around with initialize, but I want a related week object to be created as part of the initialization.
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)
I understand that this is probably not the best way, so before you shoot my method down, please provide a better solution. I will probably accept your answer 🙂
It seems like the IllegalContextError is originating from the data_mapper validators.
The data_mapper docs on validators doesn’t provide much info for a newbie to understand context AND in relation to validators.
Here is my hacky workaround. I override the validators by using the bang operator (!). The solution is as follows.