Vijay Chouhan
Vijay Chouhan

Reputation: 4883

How to delete record from only associated table with has_and_belongs_to_many relation ship

I have two model hotel and theme and both has has_and_belongs_to_many relationship

and third table name is hotels_themes, So I want to delete record only from third tables hotels_themes.

hotels_themes;
+----------+----------+
| hotel_id | theme_id |
+----------+----------+
|        8 |        4 |
|        9 |        5 |
|       11 |        2 |
|       11 |        4 |
|       11 |        6 |
|       12 |        2 |
|       12 |        5 |
+----------+----------+

I want to delete record which match hotel_id and theme_id. Like sql query delete from hotels_themes where hotel_id=9 and theme_id=5

Upvotes: 0

Views: 182

Answers (2)

akhanubis
akhanubis

Reputation: 4232

Use the method delete added to HABTM collections:

hotel = Hotel.find(hotel_id)
theme = Theme.find(theme_id)
hotel.themes.delete(theme)

Upvotes: 1

steakchaser
steakchaser

Reputation: 5249

You just need to empty out the association on either model instance depending on what you are trying to remove. For example:

hotel.themes = []
# or
theme.hotels = []

Upvotes: 0

Related Questions