1
votes

I have these models and associations. I want to reach roleable trough privilege model doesnt matter what roleable_type is(Dj or Photographer)? Use join model because privilege model will have other attributes. It is possible something like this:

class User
  has_one :privilege, dependent: :destroy
  has_one :roleable, through: :privilege
end

class Dj < ActiveRecord::Base
  has_one :privilege
  has_one :user, through: :privilege, as: :roleable
end

class Photographer < ActiveRecord::Base
  has_one :privilege
  has_one :user, through: :privilege, as: :roleable
end

class Privilege < ActiveRecord::Base
  belongs_to :user
  belongs_to :roleable, polymorphic: true
end

If i add source_type: 'Dj' to has_many :through return only with roleable_type 'Dj'. I want to do this bellow:

u = User.first
u.roleable #return privilage roleable( doesnt matter Dj or Photograher)
1
You need a Roleable class as well if you're making a join table. Did you write one yet?Trip
i want roleable to be Dj or Photograph modelGeorgi
Ah ok it sounds like you should be doing inherited classes. So instead of Photographer and DJ inheriting from ActiveRecord::Base, have them inherit from a class called Roleable. class Photographer < Roleable. Then you still have to make a roleable.rb file. And you could put all your shared methods in this as well. If this is what you want, you wouldn't need tables for photographer or DJ. just a table that represents Roleable.Trip
i will need dj and photographer tables because will contain different methods and attributesGeorgi
Ok so u.roleable could potentially return a Photgrapher object? What does it return now?Trip

1 Answers

-1
votes

I'd make those belongs_to, not that that changes anything.

class User < ActiveRecord::Base
  has_one :privilege, dependent: :destroy
  has_one :roleable, through: :privilege
end

class Dj < ActiveRecord::Base
  has_one :privilege
  belongs_to :user, through: :privilege, as: :roleable
end

class Photographer < ActiveRecord::Base
  has_one :privilege
  belongs_to :user, through: :privilege, as: :roleable
end

class Privilege < ActiveRecord::Base
  belongs_to :user
  belongs_to :roleable, polymorphic: true
end

Can you post, what u.roleable returns?