Pierre-Louis Gottfrois
Pierre-Louis Gottfrois

Reputation: 17631

Unable to copy Ruby object's attributes

I have a very painful issue here, if some one could help ?

I have a class Task with attributes and I wanted to make a bang method (because I'm changing the receiver) but I'm not able to change object attributes properly :

def reject!
    return nil if self.previous_owner.nil?
    self.delegate = false

    # Before, owner equal a User object
    self.owner = self.previous_owner # previous_owner is also a User object, but different
    self.previous_owner = nil

    return self if self.save
    raise "Can't save object"
end

This won't work because self.owner will be nil... I know this is because telling Ruby that self.owner = self.previous_owner and then changing self.previous_owner to nil.

So how can I avoid this ? I tried clone and dup method, but I'm not sure I want to have a new copied User object...

Strange thing too, if I try this in rails console :

a = 'Foo'
b = a
a = 'New value'

puts a # "New value"
puts b # "Foo"

So I think I'm missing something...

Upvotes: 0

Views: 176

Answers (1)

nathanvda
nathanvda

Reputation: 50057

Please note that self.owner and self.previous_owner are convenience methods provided by Rails. The actual fields should be called something like owner_id and previous_owner_id and contain the actual id of the User you want to link to.

So a simpler, and failsafe approach is to write

self.owner_id = self.previous_owner_id
self.previous_owner = nil # this will unlink the previous owner
self.save!

and self.save! will raise if the save fails.

Upvotes: 2

Related Questions