Rails 4: base class type of polymorphic set instead of inherited

I have a problem with rails relationships. I have a base model ant its inherited version

class User < ActiveRecord::Base
end

class Admin < User
end

Next I have a membership model with polymorphic association

class Membership < ActiveRecord::Base
  belongs_to :group
  belongs_to :membershipable, polymorphic: true
end

When I tried to create a new instance of the Membership model by typing, for example,

Membership.new group: Group.first, membershipable: Admin.first

memberable_type sets the value to "User" instead of "Administrator". So I create a callback before_validation

def proper_sti_type
  self.membershipable_type = memebrshipable.class.name
end

and it works, but I think this is the best way to do this. Maybe someone knows a better solution?

thank

Tom

+4
source share
1 answer

, _ "Admin"

class User < ActiveRecord::Base
  has_many :memberships, as: :membershipable
end

, , . , :

Membership.new group: Group.first, membershipable: Admin.first

memberable_type "".

0

Source: https://habr.com/ru/post/1539469/


All Articles