Topic: habtm migrate question


any help with writing this migrate file most appreciated:

has_and_belongs_to_many :photogalleries

has_and_belongs_to_many :images

--------current migrates-----
create_table :images do |t|
      t.column :title, :string
      t.column :photogallery_id, :int

create_table :photogalleries do |t|
      t.column :name, :string
      t.column :article_id, :int

create_table "images_photogalleries", :id => false do |t|
    t.column "image_id", :int
    t.column "photogallery_id", :int

----add_images_photogalleries_data migrate?-----
My question is:

how do i write a simple migrate file that will push images 1,2 and 3 into photogallery 1? using the id int as the link...

thanks for any help.

Re: habtm migrate question

Is this what you want?

photogallery = Photogallery.find(1)
photogallery.images << Image.find(1)
photogallery.images << Image.find(2)
photogallery.images << Image.find(3)

That should add images 1, 2, and 3 to photogallery 1.

There's a couple other ways you can do this depending on what you want. If you want photogallery 1 to only contain images 1, 2, and 3, try this:

Photogallery.update(1, :image_ids => [1, 2, 3])

If you want images 1, 2, and 3 to only be part of photogallery 1 and no other, try this:

Image.update(1, :photogallery_ids => [1])
Image.update(2, :photogallery_ids => [1])
Image.update(3, :photogallery_ids => [1])

These are all untested though. Hope that helps.

Last edited by ryanb (2006-08-25 02:57:37)

Railscasts - Free Ruby on Rails Screencasts

Re: habtm migrate question

thanks, that worked. i was getting an unitialised constant error with the normal ImagePhotogallery.create method

thanks for the speedy reply