I have users and companies tables where users belongs_to companies. def signup @company = Company.new(params[:company]) @user = User.new(params[:company]) @user.company = @company if @user.valid? and @company.valid? @company.save @user.save end end How can I make this into a transaction? Is this a candidate for a distributed transaction? If so, from what I understand from the API, I'd have to do: Company.transaction do @company.save User.transaction do @user.save end end which is apparently unsafe. Or should I do this in SQL? Help!
on 2006-01-26 12:23
on 2006-01-26 13:50
I think I've got the answer: def signup @user = User.new(@params[:user]) @user.company = Company.new(@params[:company]) @user.address = Address.new(@params[:address]) if @request.post? and @user.valid? User.transaction do @user.save #return @user.company.addresses << @user.address end flash[:notice] = 'Signup successful' redirect_to :action => 'welcome', :user => @user else flash.now[:notice] = 'Signup failed' end end In the log: BEGIN INSERT INTO companies (`name`) VALUES ('acme') INSERT INTO addresses (`company_id`, `street`) VALUES (NULL, 'Smith Street') INSERT INTO users (`name`, `address_id`, `company_id`) VALUES VALUES ('John', 13, 8) SELECT * FROM addresses WHERE addresses.company_id = 8 37mUPDATE addresses SET `street` = 'Dunkerstr', `company_id` = 8 WHERE id = 13 COMMIT Did a rudimentary test (uncommented 'return') and nothing was committed.