
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
-
Piotr Solnica (solnic) January 8th, 2011 @ 01:10 PM
- Milestone set to 1.1
- State changed from unconfirmed to confirmed
- Assigned user set to Piotr Solnica (solnic)
- Milestone order changed from 196326 to 0
-
Piotr Solnica (solnic) January 12th, 2011 @ 07:39 AM
- State changed from confirmed to resolved
(from [045b9074617820dc4f19bd7c2466b05303898f3e]) Support changing value of a foreign key in m:1 relationship
This makes possible to explicitly update a foreign key, for example:
john = User.create jane = User.create
post = Post.create :user => john post.update :user_id => jane.id # that used to not work
Additionally it makes a child resource to update its parent if an FK was changed:
post.user_id = john.id post.user # and it's john again
[#1471 state:resolved] https://github.com/datamapper/dm-core/commit/045b9074617820dc4f19bd...
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.
Create your profile
Help contribute to this project by taking a few moments to create your personal profile. Create your profile »
People watching this ticket
Tags
Referenced by
-
1471 Setting child key on belongs_to relationship is not persisted [#1471 state:resolved] https://github.com/datamapper/dm-...