Topic: HABTM Relationship Problem

Hello Everyone, my first post here.

I am getting some very strange behaviour with a habtm relationship.

It is probably eaisiest to explain if i first tell you what this system is designed to do.

Thes system is for my dissertation at university, i am making a system that the user can scan a barcode of a product and see nutritional information and allergies.

For the system the user can scan a barcode, this finds the related product then stores this product firstly in an array of products and secondly in a variable called @lastScanned until it is overwritten. Once the product has been scanned, information is displayed on the screen, the nutritional information is fine. I then loop through the ingredients with the loop below

<% for ingredient in @lastScanned.product.ingredients%>

this has a habtm relationship and works fine. Then inside this loop i try to get all the allergies relating to that ingredient by the loop below

<% for allergy in ingredient.allergies%>

this allso has a link table between called allergies_ingredients and the allergy class and the ingredient class have a habtm relationship. The problem is though, this code updates the database, it sets all records in my link table to only one allergy for each ingredient. Any help with this would be greatly appreciated.

Thank you

also if someone could tell me how to post code correctly in here i would be very appreciative

Tom

Re: HABTM Relationship Problem

It updates the database? That is strange. Are you certain this is the exact statement which is doing the updating? Perhaps there's another call which is the problem. If you aren't sure, please post the surrounding code.

The only other thing I can think of is if there's a method called "allergies" in the Ingredient class which is overriding the default Active record behaviour and causing it to update the database.

Railscasts - Free Ruby on Rails Screencasts

Re: HABTM Relationship Problem

somehow the problem is in my db, i am using mysql, i press refresh then put some data in, i then press refresh again and the data changes any ideas?

Re: HABTM Relationship Problem

I can't tell what the problem is without the code, can you post that? The two lines you posted above shouldn't cause changes in the database.

BTW, you can post code between [ code=ruby ] [ /code ] tags (without the spaces).

Railscasts - Free Ruby on Rails Screencasts