我的应用程序上有评论家和电影,我正在添加crtics功能,以便将电影添加到他们的收藏夹中。现在添加或删除都不起作用。在尝试添加时,它会尝试发布补丁请求而不是帖子。在尝试删除时,它无法使用删除方法,因为我不认为它找到了要删除的对象。不知道为什么会这样。我将在下面添加所有代码和一些服务器日志。真的需要一些帮助来解决这个问题。
查看:
<%= form_for(current_critic.favorites.create, remote: true) do |f| %>
<%= hidden_field_tag :movie_id, @movie.id %>
<%= f.submit "Favorite" %>
<% end %>
其他
<%= form_for(current_critic.favorites.find_by(movie_id: @movie.id), html: { method: :delete }, remote: true) do |f| %>
<%= f.submit "Un-Favorite" %>
<% end %>
控制器
class FavoritesController < ApplicationController
def create
movie = Movie.find(params[:movie_id])
current_critic.favorite(movie)
redirect_to current_critic
end
def destroy
movie = Movie.find(params[:id])
current_critic.un_favorite(movie)
redirect_to current_critic
end
end
来自评论家模型的适用代码
has_many :favorites, dependent: :destroy
has_many :movies, through: :favorites
def favorite(movie)
favorites.create(movie_id: movie.id)
end
def un_favorite(movie)
favorites.find_by(movie_id: movie.id).destroy
end
电影模型的适用代码
has_many :favorites, dependent: :destroy
has_many :critics, through: :favorites
最喜欢的模特
class Favorite < ActiveRecord::Base
belongs_to :critic
belongs_to :movie
end
适用路线
resources :favorites, only: [:create, :destroy]
尝试添加到收藏夹时的服务器日志
Started PATCH "/favorites/28" for 99.39.164.184 at 2015-12-01 02:42:17 +0000
ActionController::RoutingError (No route matches [PATCH] "/favorites/28"):
尝试取消收藏时的服务器日志
Started DELETE "/favorites/27" for 99.39.164.184 at 2015-12-01 03:18:24 +0000
Processing by FavoritesController#destroy as JS
Parameters: {"utf8"=>"✓", "commit"=>"Un-Favorite", "id"=>"27"}
Movie Load (0.1ms) SELECT "movies".* FROM "movies" WHERE "movies"."id" = ? LIMIT 1 [["id", 27]]
Completed 404 Not Found in 2ms (ActiveRecord: 0.1ms)
ActiveRecord::RecordNotFound (Couldn't find Movie with 'id'=27):
app/controllers/favorites_controller.rb:10:in `destroy'
提前致谢。如果任何其他代码有帮助,请告诉我。
更新:我刚刚在控制台中测试了最喜欢和不喜欢的方法,它们都有效;然而,一些奇怪的事情正在发生,其中id似乎没有增加一个而是一个看似随机的数字。
答案 0 :(得分:0)
current_critic.favorites.create
,这会返回已有ID的记录,因此form_for
会将其解析为update
而不是create
}。 =&GT;解决方案:替换为current_critic.favorites.new
Favorite
的ID但用于查找Movie
=&GT;解决方案:
def destroy
favorite = current_critic.favorites.find(params[:id])
favorite.destroy
redirect_to current_critic
end