我正在处理添加到收藏夹功能,用户点击链接并向他的收藏夹添加资源,然后再次点击以删除它。问题是无论我对我的代码做什么,Rails都会继续喜欢除了我正在寻找的问题之外的任何东西
免责声明:在我的代码中,我拼错了最喜欢的字,请原谅我
Controller
class FavoritesController < ApplicationController
def favor
@question = Question.find_by(params[:id])
@favorite = Favorite.new
@favorite.user = current_user
@favorite.question = @question
@favorite.save
redirect_to :back
end
def unfavor
@question = Question.find_by(params[:id])
@favorite = current_user.favorites.find_by(question_id: @question)
@favorite.destroy
redirect_to :back
end
end
路由
concern :favoriteable do
post 'favorites/favor', to: 'favorites#favor', as: :favor
post 'favorites/unfavor', to: 'favorites#unfavor', as: :unfavor
end
resources :questions, concerns: [:commentable, :favoriteable] do
resources :answers
end
问题#节目
span
- if current_user.favorites.exists?(question_id: @question)
= link_to 'Unfav this', question_unfavor_path(@question), method: :post
- else
= link_to 'Fav this', question_favor_path(@question), method: :post
记录(注意33如何变为15 )
Started POST "/questions/33/favorites/favor" for 127.0.0.1 at 2014-07-01 19:10:02 +0400
Processing by FavoritesController#favor as HTML
Parameters: {"authenticity_token"=>"SjOLDdIx4DMfHwLJLBdNd6N12tLNyN+QdaMT0OlpOCU=", "question_id"=>"33"}
Question Load (0.7ms) SELECT "questions".* FROM "questions" LIMIT 1
User Load (0.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1 [["id", 11]]
(0.1ms) BEGIN
SQL (0.3ms) INSERT INTO "favorites" ("created_at", "question_id", "updated_at", "user_id") VALUES ($1, $2, $3, $4) RETURNING "id" [["created_at", "2014-07-01 15:10:02.490036"], ["question_id", 15], ["updated_at", "2014-07-01 15:10:02.490036"], ["user_id", 11]]
(1.0ms) COMMIT
Redirected to http://localhost:3000/questions/33
无法弄清楚,请帮忙!
答案 0 :(得分:3)
find_by
与Question.find_by(id: params[:id])
等属性一起使用。您使用不正确,即未指定属性名称。
当你这样做时
@question = Question.find_by(params[:id]) ## in "favor" and "unfavor" actions
它等同于做
@question = Question.find_by(nil)
nil
的原因:请注意服务器日志中生成的params
哈希值,您收到params[:question_id]
而非params[:id]
。因此,params[:id]
是nil
。
因此,形成的查询类似于:
SELECT "questions".* FROM "questions" LIMIT 1
最有可能返回questions
表中的第一条记录。这就是您使用id = 15
获得相同问题记录的原因。
要解决此问题,您需要使用以下内容更新favor
和unfavor
操作:
@question = Question.find(params[:question_id]) ## Using "find" which searches a record based on "id" attribute
-OR -
@question = Question.find_by(id: params[:question_id]) ## Using "find_by" and specifying "id" attribute
我建议您使用第一个选项,即find
作为基于id
(主键)搜索时获取结果的更加语义的方法
答案 1 :(得分:2)
您的参数正在发布:question_id
而不是:id
在视图中切换到此
- if current_user.favorites.exists?(question_id: @question)
= link_to 'Unfav this', question_unfavor_path(id: @question.id), method: :post
- else
= link_to 'Fav this', question_favor_path(id: @question.id), method: :post
或者在你的控制器中切换到这个(这在我看来更干净)
@question = Question.find(params[:question_id])