leomayleomay
leomayleomay

Reputation: 563

Override the original record while creating a new one

class Company < ActiveRecord::Base
  has_one :ceo, :dependent => :destroy
end

class Ceo < ActiveRecord::Base
  belongs_to :company
end

c = Company.find(1)
c.create_ceo(:name => "Jobless", :age => 46, :gender => "male") # This will create a new CEO named "Jobless"
c.create_ceo(:name => "Baldmer", :age => 56, :gender => "male") # This will create a new CEO named "Baldmer"

Once the 2nd CEO created, the first CEO's company_id is set to be nil, how could I remove the 1st CEO from the db once the 2nd one is created?

Upvotes: 1

Views: 226

Answers (2)

Harish Shetty
Harish Shetty

Reputation: 64363

Try this:

class Company < ActiveRecord::Base
  has_one :ceo, :dependent => :destroy

  def assign_ceo options ={}
    Company.transaction do
      ceo.try(:destroy)
      create_ceo(options)
    end
  end
end

Now:

company.assign_ceo(:name => "Foo", ...)

Upvotes: 0

jefflunt
jefflunt

Reputation: 33954

The :dependent => :destroy doesn't destroy the old Ceo record when a new value is assigned. All that does is destroy the Ceo object, in the event that the Company object is destroyed.

If you're simply changing Ceo's you can either change the fields on the existing Ceo record:

c.ceo.name = "Baldmer"
c.ceo.age = 56
c.ceo.save
# This doesn't create a new record, it simply changes the only already in place

Or the following, which both changes the attributes, and saves the record in one shot.

c.ceo.update_attributes({:name => "Baldmer", :age => 56, :gender => "male"})

Or explicitly destroy the old Ceo record after the new one is created:

c = Company.find(1)
jobless = c.create_ceo(:name => "Jobless", :age => 46, :gender => "male")
baldmer = c.create_ceo(:name => "Baldmer", :age => 56, :gender => "male")

jobless.destroy     # you need to explicitly destroy this Ceo record.

On a side note, if you stay with what you've got, and you're interested in getting a list of CEOs that are in the DB, but which are not currently working for companies, you could do:

 > ceos_without_companys = Ceo.find(:all, :conditions => ":company_id = nil")
=> ["<#Ceo, :name => "Jobless", :age => 46, :gender => "male">]

Upvotes: 2

Related Questions