trickydiddy trickydiddy - 1 month ago 4
Ruby Question

Routes/Controller issues with "unfavorite action"

I have implemented an add to favorites feature with a has_many :through association. A user is now able to favorite or unfavorite a room in the room show.html.erb view. On a different controller and view I want to display all the favorite rooms of the logged in user.

And I want that the user is able to delete every favorite room. Showcasing all the rooms is no problem unfortunately I can't make this work with the unfavorite button.

How can I make this work?

enter image description here

rooms_controller.rb

before_action :set_room, only: [:show, :favorite]
...
def favorite
type = params[:type]
if type == "favorite"
current_user.favorites << @room
redirect_to wishlist_path, notice: 'You favorited #{@room.listing_name}'

elsif type == "unfavorite"
current_user.favorites.delete(@room)
redirect_to wishlist_path, notice: 'Unfavorited #{@room.listing_name}'

else
# Type missing, nothing happens
redirect_to wishlist_path, notice: 'Nothing happened.'
end
end

private
def set_room
@room = Room.find(params[:id])
end


static_pages_controller.rb

def wishlist
end


wishlist.html.erb

<div>
<% current_user.favorites.each do |room| %>
<%= room.listing_name %>
<%= link_to "unfavorite", favorite_room_path(@room, type: "unfavorite"), method: :put %>
<% end %>
</div>


routes.rb

Rails.application.routes.draw do

root 'static_pages#welcome'
get 'wishlist' => 'static_pages#wishlist'

resources :rooms, only: [:index, :show] do
resources :reservations, only: [:create]
resources :reviews, only: [:create, :destroy]
end

resources :rooms do
put :favorite, on: :member
end

Answer

In whishlist.html.erb you are using '@room' instead of 'room'. @room is only set in the rooms controller, not the static pages controller.

Comments