How to cast an ActiveRecord object to another class when using STI?
I'm currently using ActiveRecord single table inheritance.
How can I cast one of my models from type A to B? They h开发者_如何学Goave the same parent.
#becomes
is what you are looking for:
http://api.rubyonrails.org/classes/ActiveRecord/Persistence.html#method-i-becomes
You shouldn't need to cast since Ruby does not perform any type-checking at compile time. What are you trying to accomplish?
Say you have a class Dad
, and child classes Son
and Daughter
.
You could just have a variable @dad and store in it either a Son
or Daughter
object, and just treat it as if it were a Dad
. As long as they respond to the same methods, it makes no difference. This is a concept called "duck typing".
If we have something like following
class A < ApplicationRecord
end
Class B < A
end
we can use becomes
a = A.first
b = a.becomes(B)
or vice versa
Create a new instance of B to setting the values for attributes it shares with A.
Something like:
class C < ActiveRecord::Base
end
class A < C
end
class B < C
end
@a = A.new(...)
@b = B.new(@a.attr1, @a.attr2, ..., @a.attrN)
精彩评论