Rails does not save the attribute that is changed

I add text to a field noteson one of my models ActiveRecord::Base, but when I save it, it does not update:

valve.notes                          
#=> "Level: Top"

valve.notes << "\nDirection: North"

valve.notes                          
#=> "Level: Top\nDirection: North"

valve.save                           
#=> true

valve.reload.notes                   
#=> "Level: Top"
+2
source share
1 answer

Concat does not tell ActiveRecord that the attribute has changed.

I thought and wanted to share it here for others (and, most likely, me!) In the future.

I did not know this, but ActiveRecord cannot determine that the attribute was changed (i.e. dirty) when you combine it, either with concat(), or <<. And since ActiveRecord saves or updates attributes that have been changed (i.e., Dirty), it does not update this attribute.

, , , , (, , , ActiveRecord:).

valve.notes            
#=> "Level: Top"

valve.notes << "\nDirection: North"

valve.changed?         
#=> false

valve.notes_changed?   
#=> false

valve.save
#=> true

valve.reload.notes
#=> "Level: Top"

API Rails.

, :

  • ActiveRecord , notes (.. ):

    valve.notes << "\nDirection: North"
    
    valve.changed?                      
    #=> false
    
    valve.notes_will_change!
    
    valve.changed?                      
    #=> true
    
  • concat() << :

    valve.notes = "#{valve.notes}\nDirection: North"
    
    valve.changed?                      
    #=> true
    

, .

JP

+8

Source: https://habr.com/ru/post/1540051/


All Articles