# Question about has\_and\_belongs\_to\_many

**URL:** <https://www.ruby-forum.com/t/question-about-has-and-belongs-to-many/90309>\
**Category:** Rails\
**Created:** [March 27, 2007, 5:55pm UTC](https://www.ruby-forum.com/t/question-about-has-and-belongs-to-many/90309 "2007-03-27T17:55:30Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![flo\_schaf](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/f/35a633/32.png) [@flo\_schaf](https://www.ruby-forum.com/u/flo_schaf)\
**Post date:** [March 27, 2007, 5:55pm UTC](https://www.ruby-forum.com/t/question-about-has-and-belongs-to-many/90309/1 "2007-03-27T17:55:30Z")

</div>

howdy!  
i have got two models: a photo model and a lightbox ( a group of photos)  
model.

they look like this:

class Lightbox \< ActiveRecord::Base  
acts\_as\_taggable  
has\_and\_belongs\_to\_many :photos  
end

class Photo \< ActiveRecord::Base  
acts\_as\_taggable  
validates\_presence\_of :filename  
has\_and\_belongs\_to\_many :lightboxes  
end

and my db migration looks like this:

class CreateLightboxes \< ActiveRecord::Migration  
def self.up  
create\_table “lightboxes” do |t|  
t.column “description”, :text  
t.column “name”, :string  
t.column “created\_at”, :date  
end

```
create_table("lightboxes_photos", :id=>false) do |t|
  t.column "lightbox_id", :integer
  t.column "photo_id", :integer
end

```

end

def self.down  
drop\_table “lightboxes”  
drop\_table “lightboxes\_photos”  
end  
end

how can i add a photo to a lightbox?  
i you need more code to help me just tell me  
thanks for your help  
flo

---

<div class="post-metadata">

**Author:** ![flo\_schaf](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/f/35a633/32.png) [@flo\_schaf](https://www.ruby-forum.com/u/flo_schaf)\
**Post date:** [March 27, 2007, 9:38pm UTC](https://www.ruby-forum.com/t/question-about-has-and-belongs-to-many/90309/2 "2007-03-27T21:38:36Z")

</div>

> how can i add a photo to a lightbox?

# add a new photo

lightbox = Lightbox.find(1)  
lightbox.photos.create(:filename =\> ‘me.jpg’)

# add an existing photo

lightbox = Lightbox.find(1)  
photo = Photo.find(1)  
lightbox.photos.push(photo)  
lightbox.save

Hope this helps.

Cheers,  
Mischa

–  
[http://boxroom.rubyforge.org](http://boxroom.rubyforge.org)
