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"一旦创建了第二个首席执行官,第一个首席执行官的company_id设置为零,那么一旦创建了第二个首席执行官,我如何从数据库中删除第一个首席执行官呢?
发布于 2011-09-14 22:18:00
当分配新的值时,:dependent => :destroy不会销毁旧的首席执行官记录。所做的全部工作就是在公司对象被销毁的情况下销毁对象。
如果您只是简单地更改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"})或者在创建新的记录后显式销毁旧的首席执行官记录:
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.另外,如果您继续使用已有的内容,并且有兴趣获得数据库中的CEO列表,但当前未在公司工作,则可以这样做:
> ceos_without_companys = Ceo.find(:all, :conditions => ":company_id = nil")
=> ["<#Ceo, :name => "Jobless", :age => 46, :gender => "male">]发布于 2011-09-15 02:13:54
试试这个:
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", ...)https://stackoverflow.com/questions/7417640
复制相似问题