Ruby on Rails:<<の助けを借りてモデル属性をmodifiyngする仮想方法は、その属性を保存できませんでした

StackOverflow https://stackoverflow.com/questions/3119008

質問

属性コメント(タイプのモデル批准があります 文章)

def Ratification < ActiveRecord::Base
  attr_accessor :add_comment
  def add_comment=(text)
    self.comment ||= ""
    self.comment << "\r\n" + text
  end
end

そして、私が使用する場合 add_comment = オブジェクトを保存する前に大丈夫です。コメントの変更が削除された後。

>> r = Ratification.last
  Ratification Load (0.6ms)   SELECT * FROM `ratifications` ORDER BY ratifications.id DESC LIMIT 1
=> #<Ratification id: 8, user_id: 686, comment: "dasads", created_at: "2010-06-25 13:16:24", updated_at: "2010-06-25 13:38:36">
>> r.comment
=> "dasads"
>> r.add_comment="text"
=> "text"
>> r.comment
=> "dasads\r\ntext"
>> r.save
  SQL (0.7ms)   BEGIN
  SQL (0.2ms)   COMMIT
=> true
>> r.reload
  Ratification Load (1.6ms)   SELECT * FROM `ratifications` WHERE (`ratifications`.`id` = 8) 
=> #<Ratification id: 8, user_id: 686, comment: "dasads", created_at: "2010-06-25 13:16:24", updated_at: "2010-06-25 13:38:36">
>> r.comment
=> "dasads"

なぜ?!

Rails 2.3.8 Ruby 1.8

役に立ちましたか?

解決

hrrrm ...それは奇妙です、私は私がやろうとするとき、私のRailsアプリから同様の動作を見ています:

@s.name << "test"

そして、リロード...元の名前はリセットされます!

ただし、 @s.name += "test"を行うと

その後、リロード後でも、新しい名前が保存されます。

なぜ<<がそのように動作しているのかはわかりませんが、通常はすべての場合にデフォルト +=になるので、以前に気づいたことはありません。 +=に変更しますか?

編集:APIを見ると、<<が元の文字列を変更し、 +または + =は古い文字列を含む新しい文字列を作成しますか?たぶん、レールは、それが新しいものとしてマークしたものだけを保存するだけです(変更するのではなく)?

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top