0

I have a model with such attributes:

  1. some_number
  2. some_string

I want to put some value in some_string depending on current value of some_number and new value of some_number on updating.

Example:

Current some_number is 4

New (updated) value of some_number is 5

I want to put 4+5 string into some_string before some_number is overwritten.

How can I get it worked?

blackst0ne
  • 681
  • 6
  • 22
  • Override the `some_number=` setter -- cf http://stackoverflow.com/questions/10464793/what-is-the-right-way-to-override-a-setter-method-in-ruby-on-rails – Bob Mazanec Nov 11 '14 at 22:45
  • Could you please explain me a bit more clearly how can I solve my problem by overriding a setter? How can I get current value and new value in that setter? – blackst0ne Nov 12 '14 at 01:31

2 Answers2

2

If I would need to modify some attribute depending on other attribute value on update event I'd do like that:

class Thing < ActiveRecord::Base
    before_update :modify_some_string
    protected
    def modify_some_string
            # some actions with self.some_string and self.some_number
            # and self.some_string_was and self.some_number_was
    end
end
exdee
  • 46
  • 5
1

Hard to tell from your question as stated, but assuming you want some_number's current value at the end of some_string...

class Thing < ActiveRecord::Base
  def initiaize
    @numbers = []
    super
  end

  def some_number=(value)
    @numbers << value
    write_attribute :some_string, @numbers.join('+')
    super
  end
end
Bob Mazanec
  • 1,121
  • 10
  • 18
  • Note that this solution applies to every change to `some_number`, independent of whether or not the model is `save`d to the database. – Bob Mazanec Nov 12 '14 at 15:32