-1

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)
JoeyC
  • 550
  • 9
  • 19
  • Can you put a little bit more work into your code example? This one does even parse. – mbj Feb 01 '13 at 13:01
  • my bad, I should have put in the finalization and initialization stuff. It may seem stupid, but I didn't think people would need to run the code to tell me why I was getting an IllegalContextError. I definitely won't make the mistake again next time. – JoeyC Feb 05 '13 at 07:45

1 Answers1

0

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.

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)
JoeyC
  • 550
  • 9
  • 19