How to belongs to many (not habtm)


biography has many picture
event has many picture

but pictures can’t belongs to event AND biography at the same time :
well, it’s certainly possible but not really ‘clean’… It means
polluting the picture model with event_id, biography_id, and some others
(article_id, page_id, …)

How can I do ?

Thanks by advance

Well, if the same picture can belong to an Event AND a biography at the
same time, it gets kinda complicated, but if one picture can only belon
to an event OR a biography, the simple solution is a polymorphoc

class Biography < ActiveRecord::Base
has_many :pictures, :as => :image

class event < ActiveRecord::Base
has_manny :pictures, :as => :image

class Picture < ActiveRecord::Base
belongs_to :image, :polymorphic => true

Now your Picture Model only needs 2 special fields:

image_id (Integer) = the foreign key of the object it belongs_to
image_type (string) = the Class Name of the object it belongs_to

those 2 fields are handled by ActiveRecord, you dont have to provide
the values yourself …

now you can do: # get all Pictures of an event
… OR …
@event =
… ETC …
and all the other stuff you could do with a simple
has_many <-> belongs_to relationship.

Read more here:

Theres also a way for polymorphic habtm relationships, and an example
in the wiki, but i didnt fully understand it yet :smiley:

Thanks a lot ! Really !
After several month or RoRing I had never heard about this stuff… :frowning:

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs