Ruby on rails: virtual method that modifiyng model attributes with help of << couldn't save that attribute

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

Question

There is model Ratification with attribute comment (of type text)

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

And if I use add_comment= it is ok before I save the object. After save comment changes was dropped.

>> 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"

Why?!

Rails 2.3.8 Ruby 1.8

Was it helpful?

Solution

Hrrrm...that IS weird, I'm seeing similar behavior from my rails app when I try to do:

@s.name << "test"

and then reload...the original name is getting reset!

HOWEVER, if I do @s.name += "test"

then even after reloading, the new name is saved.

I'm not sure why << is behaving like that, but I usually default to += in all cases, so I've never noticed it before. Does changing to += help you?

Edit: Looking at the API, maybe it's because << modifies the original string, whereas + or += makes a NEW string, that contains the old one? Maybe rails somehow only saves things that it has marked as new (rather than modified?)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top