If I have ProductGroups which can have any number of Products, how can I remove an association between the two? Example: Products: id, name, cost 1, tester1, 50 2, tester2, 60 ProductGroups: id, name 1, main MappingTable id, product_id, product_group_id 1, 1, 1 1, 2, 1 In the above example, Products 1 and 2 are attached to ProductGroup 1. If I do: ProductGroup.find(1).Products Then I retrieve both products. How can I make it so that Product 1 is no longer attached to *any* ProductGroup?
On 5/8/05, Colin Ramsay <colinramsay-BFpX1XrDWuBdtzWjJqcUOrVCufUGDwFn@public.gmane.org> wrote:> MappingTable > id, product_id, product_group_id > 1, 1, 1 > 1, 2, 1 > > In the above example, Products 1 and 2 are attached to ProductGroup 1. > If I do: > > ProductGroup.find(1).Products > > Then I retrieve both products. How can I make it so that Product 1 is no > longer attached to *any* ProductGroup?do some custom sql: delete from MappingTable where product_id=1; -- Urban Artography http://artography.ath.cx
Rob Park wrote:>do some custom sql: > >delete from MappingTable where product_id=1; >Bah! I was hoping there''d be some fancy dancy way! Thanks very much.
Colin Ramsay wrote:> If I have ProductGroups which can have any number of Products, how can I > remove an association between the two? Example: > > Products: > id, name, cost > 1, tester1, 50 > 2, tester2, 60 > > ProductGroups: > id, name > 1, main > > MappingTable > id, product_id, product_group_id > 1, 1, 1 > 1, 2, 1 > > In the above example, Products 1 and 2 are attached to ProductGroup 1. > If I do: > > ProductGroup.find(1).Products > > Then I retrieve both products. How can I make it so that Product 1 is no > longer attached to *any* ProductGroup?If you have ProductGroup HABTM Products and vice versa, you could use something along the lines of: dead_product = Product.find(1) dead_product.groups.clear From your example data I''m not sure how you have your associations setup. Note that if you are using has_and_belongs_to_many, you likely don''t want an `id` field on your join table. Quote from API[1]: Note that any fields in the join table will override matching field names in the two joined tables. As a consequence, having an "id" field in the join table usually has the undesirable result of clobbering the "id" fields in either of the other two tables. [1] http://rails.rubyonrails.com/classes/ActiveRecord/Associations/ClassMethods.html#M000436 AR::Associations has_and_belongs_to_many -- Lee
Lee O''Mara wrote:> Note that any fields in the join table will override matching > field names in the two joined tables. As a consequence, having > an "id" field in the join table usually has the undesirable > result of clobbering the "id" fields in either of the other two > tables.Strange. I haven''t noticed any ill-effects, but thanks for the heads-up. Colin