How would you go about linking up two columns with one parameter?
Say I have multiple user classes Foo and Bar.
They each have many Childs. Child belongs to one of the user classes.
I have two DB columns in Child, user_type and user_id. I would like to be able to update Child with its parent user by doing:
Child.first.update(user: Foo.first)
or
Child.first.update(user: Bar.first)
I've tried defining custom methods in the ActiveRecord::Base file of Child, but it only seems to be able to retrieve.
#child.rb
class Child < ActiveRecord::Base
def user
if user_type == 'Foo'
return Foo.find(user_id)
elsif user_type == 'Bar'
return Bar.find(user_id)
end
end
def user=(parent)
user_type = parent.class.base_class.name
user_id = parent.id
end
Having the above code, Child.first.user works but Child.first.update(user: Foo.first) does not.