trickydiddy
trickydiddy

Reputation: 587

How can I destroy a record in a join table with has_and_belongs_to_many association?

I am creating an app where a user can favorite a room. I accomplished this with a has_and_belongs_to_many association. I chose this instead of has_many :through because this requires a third model (which could be Favorite) and it would only be used to create the association.

How can I add a unfavorite(destroy) action into the view or controller?

rooms_controller.rb

def favorite
    room = Room.find(params[:id])
    current_user.rooms << room unless current_user.rooms.exists?(room)
    redirect_to wishlist_path
end

routes.rb

post 'rooms/:id/favorite' => 'rooms#favorite'

show.html.erb (room)

<div>Add to Wishlist</div>
<%= form_tag(controller: "rooms", action: "favorite", method: "post") do %>
    <%= submit_tag "Favorite"%>
<% end %>

wishlist.hmtl.erb

<% current_user.rooms.each do |room| %>
    <%= room.listing_name %>
<% end %>

Upvotes: 1

Views: 1138

Answers (2)

Chris Brisson
Chris Brisson

Reputation: 310

I believe this should work. Say you have the room to unfavorite for the user and save the room as @room. Then you can simply do current_user.rooms.delete(@room) and I believe rails will do the rest. This works with has_many but I cannot currently test with an has_and_belongs_to_many association, it's worth a try!

Documentation

Upvotes: 2

dimitry_n
dimitry_n

Reputation: 3019

I chose this instead of has_many :through because this requires a third model (which could be Favorite) and it would only be used to create the association.

I would actually go with the opposite, and pick has_many through. Then, to remove a room from favorites, you can simply destroy the association by doing:

...
FavoriteRoom.find_by(
  user_id: current_user.id,
  room_id: params[:room_id]
).destroy
...

Upvotes: 1

Related Questions