Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add existing records to has_many without it saving to the DB immediately?

Suppose I've got this:

class Pirate < ActiveRecord::Base
  has_many :parrots
  validates_presence_of :name
end

class Parrot < ActiveRecord::Base
  belongs_to :pirate
end

And I've got existing Pirates and Parrots with ids 1 to 10. Now I'd like to do this:

p = Pirate.first
p.name = nil
p.parrot_ids = [1,2,3]
p.save if p.valid?

Because the pirate object is not valid (it's missing a name) I don't want it to be saved. However, the parrots are linked to the pirate now, and it's committed in the database.

How can I assign the parrots, but have the links to the parrots only saved to the database when p.save is successful? I.e., how can I save the pirate and the links to the parrots in one transaction?

like image 779
Jim Soho Avatar asked Sep 03 '11 04:09

Jim Soho


People also ask

How to save only the records added to the context?

The EF will save only those records, which you add to the context using the Add method or AddRange method. For Example, consider the following example. We retrieve all the Departments into the deps List. We create two more Departments (Dept3 & Dept4) and add it the deps list.

How to add multiple records or objects to a dbset?

Whenever we add an entity using the Add or AddRange method, the context marks the state of the entity as added. Hence when we call the SaveChanges Context will create an insert query and sends it to the database. You can add multiple records or multiple objects using the AddRange method of DbSet as shown in the following code.

How many records can be added to a list in MySQL?

The List contains 6 records. We add two more records making it 8 records. Now we use the AddRange method and then call the SaveChanges method The SaveChanges inserts 8 records to the database. Although the six records already exist in the database. The Add or AddRange does not check if the records exist or not.

How to insert a new employee and Department to the database?

The newly created Employee is added to the Employees Navigation property. Now, when we add the new dep to the context using the Add method it also adds the Employee automatically. Hence SaveChanges will insert a new employee and department to the database.


1 Answers

You should probably take a look at the Active Record transactions. You can wrap your code as you have it in a transaction block. Transactions are protective blocks where SQL statements are only permanent if they can all succeed as one atomic action

http://api.rubyonrails.org/classes/ActiveRecord/Transactions/ClassMethods.html

like image 122
AfDev Avatar answered Oct 18 '22 06:10

AfDev