在创建新记录时覆盖原始记录

时间:2011-09-14 14:03:38

标签: ruby-on-rails activerecord

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"

第二个CEO创建后,第一个CEO的company_id设置为nil,一旦第二个CEO被创建,我怎么能从数据库中删除第一个CEO?

2 个答案:

答案 0 :(得分:2)

分配新值时,:dependent => :destroy不会破坏旧的Ceo记录。所有这一切都会破坏Ceo对象,如果公司对象被销毁,则

如果您只是改变Ceo,您可以更改现有Ceo记录中的字段:

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

或者以下内容,它们都会更改属性,并一次性保存记录。

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

或者在创建新记录后明确销毁 Ceo记录:

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.

另一方面,如果你坚持你所拥有的,并且你有兴趣获得数据库中的首席执行官名单,但目前没有为公司工作,那么你可以:

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

答案 1 :(得分:0)

试试这个:

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

现在:

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