t56k
t56k

Reputation: 7011

Rails: one of many parents

If I have a model that can belong to one of ten other models, will I need ten different _id attributes in the model, leaving nine blank with every record? Or is there a better way to arrange it?

Thanks.

Upvotes: 2

Views: 54

Answers (2)

lurker
lurker

Reputation: 58324

As Jakub suggests, you can use a polymorphism as follows:

class Bar < ActiveRecord::Base
  belongs_to :foo, polymorphic: true
  ...
end

class Foo1 < ActiveRecord::Base
  has_many :bars, as: :foo
  ...
end

class Foo2 < ActiveRecord::Base
  has_many :bars, as: :foo
  ...
end

...

class Foo9 < ActiveRecord::Base
  has_many :bars, as: :foo
end

This will use a single id attribute in the bars table, but include an extra type field to specify which foo type it's referring to.

Upvotes: 2

Jakub Kuchar
Jakub Kuchar

Reputation: 1665

How about polymorphic association? If you need one model belonging to to many others models.Then you just need _id and _type which wont be empty.http://guides.rubyonrails.org/association_basics.html#polymorphic-associations

I need ten different _id attributes in the model, leaving nine blank with every record? - NO

Upvotes: 1

Related Questions