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

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

For example, my model has a raw_topic column. When raw_topic set, I want artist and song_title be set based on the contents of raw_topic . Ideally, I would like to override the raw_topic= method, but the rails don't seem to like it.

What is the right way to do this? Is callback the only way?

+4
source share
1 answer

You can do it as follows:

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

This way you can make sure that you still have a raw theme if you need to act.

+9
source

Source: https://habr.com/ru/post/1305289/


All Articles