⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 15 - using transactions in activerecord.rb

📁 O Reilly Ruby Cookbook source code
💻 RB
字号:
require 'cookbook_dbconnect'activerecord_connect # See chapter introductionclass User < ActiveRecord::Base  has_and_belongs_to_many :blog_postsendclass BlogPost < ActiveRecord::Base  has_and_belongs_to_many :authors, :class_name => 'User'end#---require 'active_record/transactions'class BlogPost  def BlogPost.create_from_new_author(author_name, title, content)    transaction do      author = User.create(:name => author_name)      raise 'Random failure!' if rand(2) == 0      create(:authors => [author], :title => title, :content => content)    end  endend#---BlogPost.create_from_new_author('Carol', 'The End Is Near',                                 'A few more facts of doom...')# => #<BlogPost:0xb78b7c7c ... ># The method succeeded; Carol's in the database:User.find(:first, :conditions=>"name='Carol'")# => #<User:0xb7888ae4 @attributes={"name"=>"Carol", ... }># Let's do another one...BlogPost.create_from_new_author('David', 'The End: A Rebuttal',                                 'The end is actually quite far away...')# RuntimeError: Random failure!# The method failed; David's not in the database:User.find(:first, :conditions=>"name='David'")# => nil#---

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -