Rails:最喜欢的模特有效但 favorite/unfavorite 链接无效

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

我按照 Thomas 发布的第一个答案中的步骤进行操作 here

我可以进入 Heroku 控制台并由用户手动收藏照片,这样模型就可以正确设置并正常工作,但我的 favorite/unfavorite 链接无法正常工作。

<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 日志

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

照片控制器

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

只需将此行添加为 PhootosController

favorite 方法的第一行
@phooto = Phooto.find(params[:id])

老实说,更好的模式是根据 HTTP verb:

匹配 favorite 路由
#config/routes.rb
resources :users
resources :phootos do
   match :favorite, on: :member, via: [:put, :delete]
end

这将消除路径中的 type 参数(导致问题):

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

您必须更改控制器以处理请求和变量:

def favorite
  @phooto = Phooto.find params[:id]

  if request.put?
      current_user.favorites << @phooto
      redirect_to :back, notice: 'You successfully favorited #{@phooto.name}'
  elsif request.delete?
      current_user.favorites.delete(@phooto)
      redirect_to :back, notice: 'You successfully unfavorited #{@phooto.name}'
  else
      redirect_to :back, notice: 'Nothing happened.'
  end    
end