activerecord - Rails has_many relationship where the "many" side can be of a different Type? -


i use activerecord model following case scenario:

i have user has many favorites, favorite can either profile or group.

the relationships this:

models

when access favorites user has; in...

> user.favorites 

i should array contains profile and/or group activerecord objects.

[#<profile id:1 ... >, #<group id ... >, #<profile ...>, #<group ...>] 

is possible? rails-way this?

thank you, , kind regards,

you can use polymorphic associations below:

class user < activerecord::base   has_many :favorites end  class favorite < activerecord::base   belongs_to :user   belongs_to :favoriteable, polymorphic: true end  class profile < activerecord::base   has_one :favorites, as: :favoriteable end  class group < activerecord::base   has_one :favorites, as: :favoriteable end 

for detailed explanation example: read polymorphic associations in rails official guide.


Comments

Popular posts from this blog

php - mySql Join with 4 tables -

css - Text drops down with smaller window -

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -