Has_and_belongs_to_many porblem

Hello, I’m new to this list (and rails, too).

I have a problem with has_and_belongs_to_many. I can’t find a real
example for read the data from the other db-table. Can’t view this
data. I have some images with any tags. One image can have many tags
and a tag can have many images → many-to-many.

I have write this code:

MY DATABASE (MySQL):

CREATE TABLE images (
id INT NOT NULL auto_increment,
image_url VARCHAR(200) NOT NULL,
PRIMARY KEY (id)
);

CREATE TABLE tags (
id INT NOT NULL auto_increment,
name VARCHAR(100) NOT NULL,
PRIMARY KEY (id)
);

CREATE TABLE images_tags (
image_id INT NOT NULL,
`tag_id’ INT NOT NULL,
CONSTRAINT fk_cp_image FOREIGN KEY (image_id) REFERENCES images(id),
CONSTRAINT fk_cp_tag FOREIGN KEY (tag_id) REFERENCES tags(id),
PRIMARY KEY (image_id, tag_id)
);

MY DB-VALUES:

images-table:
| id | image_url |
| 2 | http://www.rubyonrails.com/images/rails.png |

tags-table:
| id | name |
| 1 | Rails |

images_tags-table:
| image_id | tag_id |
| 2 | 1 |

MY MODELS:

models/image.rb:
class Image < ActiveRecord::Base
has_and_belongs_to_many :tags
end

models/tag.rb:
class Tag < ActiveRecord::Base
has_and_belongs_to_many :images
end

Now, I will display in the images-view the tags for an image. So I must
find all tags for a selectet image:

controllers/images_controller.rb (create by scaffold):
def show
@image = Image.find(params[:id])
@tag = Tag.find(params[:id])
end
end

views/images/show.rhtml:
Tags: <%=h @tag.name %>

But this will search a tag-ID 2 (because, i have select image 2) and
not the tags, for image-ID 2. “@tag=Tag.find(1)” will return “Rails”,
this work. How can I find all Tags for a image-ID? And for many tags
for one image, it will create an array? Thanks for help!

Martin

Martin,

You can access to image tags simply by acccessing @image.tags.

Jean-Etienne