Rails/ActiveRecord: save changes to a model's associated collections

前端 未结 5 1720
时光取名叫无心
时光取名叫无心 2021-01-05 08:55

Do I have to save modifications to individual items in a collection for a model, or is there a method I can call to save them when I save the model.

#save

5条回答
  •  失恋的感觉
    2021-01-05 09:27

    You have to do this yourself

    This isnt entirely true. You can use the "build" method which will force a save. For the sake of example assume that you have a Company model and Employees (Company has_many Employees). You could do something like:

    acme = Company.new({:name => "Acme, Inc"})
    acme.employees.build({:first_name => "John"})
    acme.employees.build({:first_name => "Mary"})
    acme.employees.build({:first_name => "Sue"})
    acme.save
    

    Would create all 4 records, the Company record and the 3 Employee records and the company_id would be pushed down to the Employee object appropriately.

提交回复
热议问题