I'm currently using ActiveRecord single table inheritance.
How can I cast one of my models from type A to B? They have the same parent.
I'm currently using ActiveRecord single table inheritance.
How can I cast one of my models from type A to B? They have 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".
type
field. –
Actaeon 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)
becomes
is implemented like this except that it copies more than just the attributes. See api.rubyonrails.org/classes/ActiveRecord/… and view the source code. –
Harry © 2022 - 2024 — McMap. All rights reserved.