4

I have problem with rails relations. I have base model ant his inherited version

class User < ActiveRecord::Base
end

class Admin < User
end

Next I have membership model with polymorphic association

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

When I tryied to make new instance of Membership model, by typing for example

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

membershipable_type is setting to "User" instead of "Admin". So i create before_validation callback

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

and it works, but i guess is better way to do this. Maybe someone know the better solution?

Thanks

Tom

betromatic
  • 69
  • 4
  • possible duplicate of [Why polymorphic association doesn't work for STI if type column of the polymorphic association doesn't point to the base model of STI?](http://stackoverflow.com/questions/9628610/why-polymorphic-association-doesnt-work-for-sti-if-type-column-of-the-polymorph) – BroiSatse May 06 '14 at 16:44

1 Answers1

0

You need to add this inside your User model in-order to get the membershipable_type as 'Admin'

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

This is because you are extending your admin model from user so it must have the association with membership model. Then when you do this:

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

you will get membershipable_type as "User".

Adnan Devops
  • 503
  • 2
  • 7