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

Android layout hidden on keyboard show -

google app engine - 403 Forbidden POST - Flask WTForms -

c - Why would PK11_GenerateRandom() return an error -8023? -