开发者

STI and subclasses

I want to know, what is a rails way of converting a subclass record to anothe开发者_StackOverflow社区r subclass record, just changing type isn't working and also superclass to subclass and vice versa.

Thanks in advance

Markiv


All you should have to do is change the type field. Make sure you save the record, and reload the Ruby object from the database.

If that doesn't work, can you provide some Ruby code that isolates the problem?


Are you asking how to change an object that is a subclass to different subclass of it's superclass? This isn't really possible in the OO scheme of things. It's possible to cast an object from a superclass to a subclass, but you can't cast it back, since the object may now contains variables and methods that the superclass does not.


Polymorphism in Rails will do the trick:

subclass1record.becomes(Subclass2)

Note: The new instance will share a link to the same attributes as the original class. So any change to the attributes in either instance will affect the other.

To avoid this, you can duplicate the record first:

subclass1record_new = subclass1record.dup

And then use the new record instead:

subclass1record_new.becomes(Subclass2)

http://apidock.com/rails/ActiveRecord/Persistence/becomes

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜