I have many associations in my model. Every record associated with parent object is saved every time parent is saved. It is behavious i want, just not every time. Is there a special method to save JUST the 'mother' object?
-
show d code and what you have tried?? – Hetal Khunti Dec 08 '14 at 13:09
-
i didn't try anything, and my code is not relevant, I just need a way to update_attributes of author without saving each of author.books – Leo Dec 08 '14 at 13:11
5 Answers
The ability to autosave associated models can be turned on or off on a per-association basis, like so:
class Post < ActiveRecord::Base
has_one :author, autosave: false
has_many :things, autosave: false
end
Read all about it here: https://api.rubyonrails.org/classes/ActiveRecord/AutosaveAssociation.html

- 1,725
- 1
- 19
- 28
Here is sample not sure this is what you are looking for??
class Survey < ActiveRecord::Base
has_many :questions, :dependent => :destroy
accepts_nested_attributes_for :questions, :reject_if => lambda { |a| a[:content].blank? }, :allow_destroy => true
end
class Question < ActiveRecord::Base
belongs_to :survey
has_many :answers, :dependent => :destroy
accepts_nested_attributes_for :answers, :reject_if => lambda { |a| a[:content].blank? }, :allow_destroy => true
end
Here Survey has many Questions, So I assume from your question that when survey is build up Question should not be saved?? Lets now have a look to controller of Survey.
surveys_controller.rb
def new
@survey = Survey.new
@survey.build # here I have commented below lines which create the object for questions also
# 3.times do
# question = @survey.questions.build
# 4.times { question.answers.build }
# end
end
def create
@survey = Survey.new(params[:survey])
if @survey.save
flash[:notice] = "Successfully created survey."
redirect_to @survey
else
render :action => 'new'
end
end

- 787
- 1
- 9
- 23
As far as I know, by default a belongs_to
association won't get saved if you save the parent class (model).
To enable this feature you need autosave.
Eg.
class Post < ActiveRecord::Base
has_one :author, autosave: true
end
However, looking further I found out this default behavior varies for different associations. Have a look at this answer: When will ActiveRecord save associations?
Maybe accepts_nested_attributes_for
in your model. I have the same problem. I set it as save: false
, but it doesn't make sense. I remove the accepts_nested_attributes_for
, and then it makes sense. Hope it will help you.

- 766
- 9
- 8
Unfortunately there's no such functionality.
In case of has_many association, the child is saved on saving its parent if child is #new_record?
.
I'd avoid saving it by not permitting params, if only it's modified in controller.

- 962
- 6
- 12