【问题标题】:Rails - Implementing a "like" feature and experiencing an infinite loopRails - 实现“点赞”功能并体验无限循环
【发布时间】:2016-02-23 16:52:48
【问题描述】:

老实说,我什至不知道从哪里开始解决这个问题,但我已经在我的网站上实现了“点赞”功能,当我查看控制台时,我看到了一个非常长的 SQL 语句。

我不会发布我的所有 dev.log,因为它实在是太长了,但这里是一些错误的 sn-p..

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"]]

然后它只是在大约 10,000 行上重复该 sql 语句,然后切换到此错误

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 %>

【问题讨论】:

  • 数据似乎不够
  • like.create(like: params[:like], chef: Chef.first, recipe: @recipe) 这个“喜欢”变量/方法从何而来?它似乎是您的 Like 模型,但您没有设置它。那么您可能没有发布整个代码 sn-p 吗?如果您可以发布更多信息,它可能对我们有用。你能做到吗?
  • @BryanOemar HA!接得好。你是绝对正确的......“like”不存在,它应该是“Like.create”。

标签: ruby-on-rails-4 ruby-2.2


【解决方案1】:

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

例如,如果您正在调用“like”操作,而“like”操作正在重定向回“like”操作,则会陷入循环。

如果您想留在同一页面上,请尝试渲染页面,或者在您设置变量的地方使用 redirect_to :an_explicit_action 然后渲染您想要的页面。

【讨论】:

    猜你喜欢
    • 2013-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多