Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I override the attribute assignment in an active record object?

I know you can do this with virtual attributes, but what if the column actually exists?

For example, my model has a raw_topic column. When raw_topic is set, I want artist and song_title to be set based off of raw_topic's contents. Ideally, I'd like to override the raw_topic= method, but rails doesn't seem to like that.

What's the proper way of doing this? Is a callback the only way?

like image 676
ryeguy Avatar asked Mar 27 '10 05:03

ryeguy


1 Answers

You can do it like this:

def raw_topic=(value)
  # do something with raw topic
  self[:raw_topic] = value
end

That way you can ensure you still have the raw topic if you need to act on it.

like image 115
Ryan Bigg Avatar answered Oct 05 '22 22:10

Ryan Bigg