本文介绍了Rails是不节能的改变属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对我的一个的ActiveRecord :: Base的模型,但是当我追加一些文字到注释字段保存它,它不会被更新:

valve.notes#=> 等级:顶级valve.notes<< \ nDirection:北valve.notes#=> 等级:顶级\ nDirection:北valve.save#=>真正valve.reload.notes#=> 等级:顶级

解决方案

Concat的没有告诉ActiveRecord的一个属性发生了变化。

想通了,想在这里分享给其他人(和最有可能我自己!)在未来。

我不知道这一点,但ActiveRecord的不能确定的属性已经改变(即是的的),当您将它连接,无论是与 CONCAT()<< 。而由于ActiveRecord的不仅节省或更新,已更改属性(即是的的),它不更新该属性。

这是,如果你没有意识到这一点,因为它不但不能默默偷偷摸摸的小疑难杂症,它并不认为这是失败的,在所有的(也许还没有,如果你问的ActiveRecord作者:)。

  valve.notes
#=> 等级:顶级

valve.notes<< \ nDirection:北

valve.changed?
#=>假

valve.notes_changed?
#=>假

valve.save
#=>真正

valve.reload.notes
#=> 等级:顶级
 

你可以阅读更多关于这在 Rails的API文档

解决方案

要解决这个问题,你需要做两件事情:

  1. 让ActiveRecord的知道注释属性发生了变化(即它现在的的):

      valve.notes<< \ nDirection:北
    
    valve.changed?
    #=>假
    
    valve.notes_will_change!
    
    valve.changed?
    #=>真正
     

  2. 不要使用 CONCAT()<< 追加到你的属性:

      valve.notes = valve.notes +\ nDirection:北
    
    valve.changed?
    #=>真正
     

希望帮助至少一种其他的灵魂。

JP

I am appending some text to a notes field on one of my ActiveRecord::Base models but when I save it, it doesn't get updated:

valve.notes                          
#=> "Level: Top"

valve.notes << "\nDirection: North"

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

valve.save                           
#=> true

valve.reload.notes                   
#=> "Level: Top"
解决方案

Concat doesn't tell ActiveRecord that an Attribute has changed.

Figured it out and wanted to share it here for others (and most likely myself!) in the future.

I didn't know this but ActiveRecord cannot determine that an attribute has been changed (i.e. is dirty) when you concatenate it, either with concat() or <<. And because ActiveRecord only saves, or updates, attributes that have changed (i.e. are dirty), it doesn't update that attribute.

It's a sneaky little gotcha if you're not already aware of it because it not only fails silently, it doesn't think it's failed at all (and perhaps it hasn't, if you ask the ActiveRecord authors :).

valve.notes            
#=> "Level: Top"

valve.notes << "\nDirection: North"

valve.changed?         
#=> false

valve.notes_changed?   
#=> false

valve.save
#=> true

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

You can read more about this on Rails' API Docs.

Solution

To get around this you need to do one of two things:

  1. Let ActiveRecord know that the notes attribute has changed (i.e. it is now dirty):

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

  2. Don't use concat() or << to append to your attributes:

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

Hope that helps at least one other soul.

JP

这篇关于Rails是不节能的改变属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 02:31