#1471 ✓resolved
Bernerd Schaefer

Setting child key on belongs_to relationship is not persisted

Reported by Bernerd Schaefer | January 7th, 2011 @ 05:05 AM | in 1.1

Scenario:

    class User
      include DataMapper::Resource
      property :id, Serial
    end

    class Task
      include DataMapper::Resource
      property :id, Serial
      belongs_to :user
    end

    DataMapper.finalize
    DataMapper.auto_migrate!

    user1 = User.create
    user2 = User.create

    task = Task.create(:user => user1)
    task.update :user_id => user2.id

Expected Behavior:

    task.user == user2

Actual Behavior:

    task.user == user1

Explanation:

Before the task model is saved, it's parents are saved, and the keys are wired up only by means of the @user instance variable, and not by the user_id value.

Patch:

This, at least, solves the problem for my test suite, though there may be a better way to implement it.

    module DataMapper
      module Associations
        module ManyToOne #:nodoc:
          class Relationship < Associations::Relationship
            def get!(resource)
              if parent = resource.instance_variable_get(instance_variable_name)
                parent = resource_for(resource) if parent_key.get!(parent) != source_key.get!(resource)
              end

              parent
            end
          end
        end
      end
    end

Comments and changes to this ticket

Please Sign in or create a free account to add a new ticket.

With your very own profile, you can contribute to projects, track your activity, watch tickets, receive and update tickets through your email and much more.

New-ticket Create new ticket

Create your profile

Help contribute to this project by taking a few moments to create your personal profile. Create your profile »

Referenced by

Pages