Rails - 实现 "like" 功能并经历无限循环

Rails - Implementing a "like" feature and experiencing an infinite loop

老实说,我什至不确定从哪里开始解决这个问题,但我已经在我的网站上实现了一个 "like" 功能,当我查看控制台时,我看到一个非常非常长的 SQL声明。

我不会 post 我所有的 dev.log 因为它太长了,但这里有一些错误的片段..

Started POST "/recipes/1/like?like=true" for 127.0.0.1 at 2015-11-20 22:46:45 -0500
   Processing by RecipesController#like as HTML
     Parameters: {"authenticity_token"=>"b64tIveTCtassgzKoJ/d65c72b3DfLmkC1ddQrCRBsbxnAuKMYpnz8L/+m5SsJ8to57v4sFXSkLIZB9QdFXdTQ==", "like"=>"true", "id"=>"1"}
     ^[[1m^[[35mRecipe Load (0.1ms)^[[0m  SELECT  "recipes".* FROM "recipes" WHERE "recipes"."id" = ? LIMIT 1  [["id", 1]]
     ^[[1m^[[36mCACHE (0.0ms)^[[0m  ^[[1mSELECT  "recipes".* FROM "recipes" WHERE "recipes"."id" = ? LIMIT 1^[[0m  [["id", "1"]]
     ^[[1m^[[35mCACHE (0.0ms)^[[0m  SELECT  "recipes".* FROM "recipes" WHERE "recipes"."id" = ? LIMIT 1  [["id", "1"]]

然后它只是重复 sql 语句超过 ~10,000 行,然后它切换到这个错误

15008   app/controllers/recipes_controller.rb:46:in `like'
15009   app/controllers/recipes_controller.rb:46:in `like'
15010   app/controllers/recipes_controller.rb:46:in `like'
15011   app/controllers/recipes_controller.rb:46:in `like'
15012   app/controllers/recipes_controller.rb:46:in `like'
15013   app/controllers/recipes_controller.rb:46:in `like'
15014   app/controllers/recipes_controller.rb:46:in `like'
15015   app/controllers/recipes_controller.rb:46:in `like'
15016   app/controllers/recipes_controller.rb:46:in `like'
15017   app/controllers/recipes_controller.rb:46:in `like'

我有点卡住了,我希望有人能指出正确的方向。

这是我的代码:

控制器

def like
  @recipe = Recipe.find(params[:id])
  Like.create(like: params[:like], chef: Chef.first, recipe: @recipe)
  flash[:success] = "Your selection was successful"
  redirect_to :back
end

型号:

class Like < ActiveRecord::Base
  belongs_to :chef
  belongs_to :recipe
end

我的其他手柄里有对应的"has_many"

迁移:

class CreateLikes < ActiveRecord::Migration
  def change
    create_table :likes do |t| 
      t.boolean :like
      t.integer :chef_id, :recipe_id
      t.timestamps
    end 
  end 
end

查看:

<%= link_to like_recipe_path(@recipe, like: true), method: :post do %>
  <i class="glyphicon glyphicon-thumbs-up"></i>
<% end %>

根据以上信息,我认为我可以得出的唯一结论是代码 redirect_to :back 正在调用一个操作,该操作将再次调用操作 like,这可能会导致循环。

例如,如果您正在调用 'like' 操作并且该 'like' 操作正在重定向回 'like' 操作,它将陷入循环。

如果您想停留在同一页面上,请尝试呈现该页面,或者 redirect_to:an_explicit_action 您设置变量的位置,然后呈现您想要的页面。