Search code examples
ruby-on-railsfavorites

Rails: Favorite Model working but favorite/unfavorite links not working


I followed the steps from the first answer posted by Thomas here

I can go into Heroku Console and manually favorite phootos by users so the models are setup correctly and working but my favorite/unfavorite links are not working.

<p><strong>Picture:</strong></p> 
<%= image_tag(@phooto.picture) %>

<%= link_to("< Previous", @phooto.previous) if @phooto.previous %>
<%= link_to("Next >", @phooto.next) if @phooto.next %>

<% if current_user %>
<%= link_to "favorite",   favorite_phooto_path(@phooto, type: "favorite"), method: :put %>
<%= link_to "unfavorite", favorite_phooto_path(@phooto, type: "unfavorite"), method: :put %>
<% end %>

Heroku Log

Started PUT "/phootos/24/favorite?type=favorite"
Completed 500 Internal Server Error in 2ms (ActiveRecord: 0.6ms)
ActiveRecord::AssociationTypeMismatch (Phooto(#70057240967940) expected, got NilClass(#70057199933300)):
app/controllers/phootos_controller.rb:29:in `favorite

PhootosController

def show
  @phooto = Phooto.find(params[:id])
end

def favorite  
  type = params[:type]
  if type == "favorite"
    **rb.29** current_user.favorites << @phooto
              redirect_to :back, notice: 'You successfully favorited #{@phooto.name}'

  elsif type == "unfavorite"
    current_user.favorites.delete(@phooto)
    redirect_to :back, notice: 'You successfully unfavorited #{@phooto.name}'

  else
    redirect_to :back, notice: 'Nothing happened.'
  end    
end

Phootos/show.html.erb

<p><strong>Picture:</strong></p> 
<%= image_tag(@phooto.picture) %>
<%= link_to("< Previous", @phooto.previous) if @phooto.previous %>
<%= link_to("Next >", @phooto.next) if @phooto.next %>

<% if current_user %>
<%= link_to "favorite",   favorite_phooto_path(@phooto, type: "favorite"), method: :put %>
<%= link_to "unfavorite", favorite_phooto_path(@phooto, type: "unfavorite"), method: :put %>
<% end %>

routes.rb

resources :users
resources :phootos
resources :phootos do
  put :favorite, on: :member
end

Solution

  • Just add this line as your first line in your favorite method in PhootosController

    @phooto = Phooto.find(params[:id])