我如何可以覆盖一个活动记录对象的属性赋值? [英] 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?
例如,我的模型有一个 raw_topic
列。当 raw_topic
设置,我想艺术家
和 SONG_TITLE
来根据掉 raw_topic
的内容设定。理想情况下,我想重写 raw_topic =
方法,但铁轨似乎不喜欢这样。
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?
推荐答案
您可以做到这一点是这样的:
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.
这篇关于我如何可以覆盖一个活动记录对象的属性赋值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!