Ruby on rails 当两个关联的AR对象都未保存时,我可以从另一个关联的AR对象访问信息吗?
假设我打开Rails(2.3.8)脚本控制台并尝试以下操作:Ruby on rails 当两个关联的AR对象都未保存时,我可以从另一个关联的AR对象访问信息吗?,ruby-on-rails,activerecord,Ruby On Rails,Activerecord,假设我打开Rails(2.3.8)脚本控制台并尝试以下操作: a = Account.new(:first_name) = 'foo' i = a.invoices.build p i.account.first_name Account.rb是一个模型对象,包含: 有很多发票吗 而Invoice.rb也是一个模型,包含: 属于_to:account,:validate=>true 在上面的控制台第3行中,i.account为零。我意识到,如果帐户已保存,I.account将不会为零,但我不希
a = Account.new(:first_name) = 'foo'
i = a.invoices.build
p i.account.first_name
Account.rb是一个模型对象,包含:
有很多发票吗
而Invoice.rb也是一个模型,包含:
属于_to:account,:validate=>true
在上面的控制台第3行中,i.account为零。我意识到,如果帐户已保存,I.account将不会为零,但我不希望保存帐户,除非我可以为该帐户创建有效发票。而且,仅仅为了好玩,发票验证取决于未保存帐户的某些属性
有没有办法让这一切顺利进行
最好的,
Will我通常对事务执行此操作。使用rails事务,您可以执行db交互,并在任何时候在无法验证的情况下回滚它们。例如: 在您的模型中:
def save_and_create_invoice
Account.transaction do
#first let's save the account, this will give us an account_id to work with
return false unless self.save
invoice = self.invoices.build
#setup your invoice here and then save it
if invoice.save
#nothing wrong? return true so we know it was ok
return true
else
#add the errors so we know what happened
invoice.errors.full_messages.each{|err| errors.add_to_base(err)}
#rollback the db transaction so the account isn't saved
raise ActiveRecord::Rollback
#return false so we know it failed
return false
end
end
end
在控制器中,您可以这样称呼它:
def create
@account = Account.new(params[:account])
respond_to do |format|
if @account.save_and_create_invoice
format.html
else
format.html {render :action => "new"}
end
end
end
请注意,我运行此代码并不是为了测试它,只是快速地将其输出以显示一个示例