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?
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With