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

前端 未结 5 1700
时光取名叫无心
时光取名叫无心 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.

    0 讨论(0)
  • 2021-01-05 09:33

    You can configure ActiveRecord to cascade-save changes to items in a collection for a model by adding the :autosave => true option when declaring the association. Read more.

    Example:

    class Payment < ActiveRecord::Base
        belongs_to :cash_order, :autosave => true
        ...
    end
    
    0 讨论(0)
  • 2021-01-05 09:35

    This post can be useful: http://erikonrails.snowedin.net/?p=267

    Erik describe how to use "accepts_nested_attributes_for" in the model and <% f.fields_for %> in the view to do the job.

    Its detailed description can be found in: http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html

    0 讨论(0)
  • 2021-01-05 09:36

    You have to do this yourself. Active Record does not cascade save operations in has_many relations after the initial save.

    You could automate the process with a before_save callback.

    0 讨论(0)
  • 2021-01-05 09:40

    just do a rental.dvd.save after you increment the value or in the above case you could use

    rental.dvd.increment!(:copies)
    

    which will also automatically save, note the '!' on increment!

    0 讨论(0)
提交回复
热议问题