0

having this code block of an example rails model class:

class Block < ActiveRecord::Base
  has_many :bricks, :autosave => true
  def crunch
    bricks.each do |brick|
      if brick.some_condition?
        brick.name = 'New data'
        brick.save # why do I have to call this?
      end
    end 
  end
end
class Brick < ActiveRecord::Base
  belongs_to :block, :autosave => true
end

I found that the only way to make sure the changes within the associated objects get saved for me, was to call brick.save manually. Even thought I use :autosave => true

Why?

lucapette
  • 20,564
  • 6
  • 65
  • 59
pagid
  • 13,559
  • 11
  • 78
  • 104

2 Answers2

0

Probably the autosave option has a misleading name. By the way, it's the expected behaviour. The option is meant for association. So if you modify an object in a relation and save the other object then ActiveRecord saves the modified objects. So, in your case, you could change your code to:

  def crunch
    bricks.each do |brick|
      if brick.some_condition?
        brick.name = 'New data'
      end
    end
    save # saving the father with autosave should save the children
  end
lucapette
  • 20,564
  • 6
  • 65
  • 59
0

You could use any of the helper methods available: update_attribute, update_attributes, update_column...

More info: Rails: update_attribute vs update_attributes

Community
  • 1
  • 1
fuzzyalej
  • 5,903
  • 2
  • 31
  • 49