0

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

Vijay Chouhan
  • 4,613
  • 5
  • 29
  • 35

2 Answers2

1

Use the method delete added to HABTM collections:

hotel = Hotel.find(hotel_id)
theme = Theme.find(theme_id)
hotel.themes.delete(theme)
akhanubis
  • 4,202
  • 1
  • 27
  • 19
  • But this is not optimized way to do it. I want to write sql like "delete form hotels_themes where hotel_id=11 and theme_id=6" – Vijay Chouhan Sep 09 '13 at 20:00
  • @VijayChouhan I suppose you should use [this](http://stackoverflow.com/questions/4483049/how-to-execute-a-raw-update-sql-with-dynamic-binding-in-rails) approach then. – akhanubis Sep 09 '13 at 20:03
  • @VijayChouhan I edited my answer with the Rails way of doing this. It has a minor drawback which is that `delete` takes an object as argument and not an id, so you need to fetch the `theme` first. – akhanubis Sep 09 '13 at 20:22
0

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 = []
steakchaser
  • 5,198
  • 1
  • 26
  • 34