2

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?

Leo
  • 2,061
  • 4
  • 30
  • 58

5 Answers5

2

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

cmrichards
  • 1,725
  • 1
  • 19
  • 28
0

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
Hetal Khunti
  • 787
  • 1
  • 9
  • 23
0

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?

Community
  • 1
  • 1
shivam
  • 16,048
  • 3
  • 56
  • 71
0

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.

TorvaldsDB
  • 766
  • 9
  • 8
-4

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.

amenzhinsky
  • 962
  • 6
  • 12