编辑和删除时对象ID混乱

时间:2018-07-05 07:55:39

标签: ruby-on-rails

指定所需对象的ID,而始终删除/编辑模型的第一个对象。我第一次遇到这样的问题,请检查所有内容。怎么了?

Started DELETE "/questions/6" for 127.0.0.1 at 2018-07-05 10:48:13 +0300
Processing by QuestionsController#destroy as HTML
  Parameters: {"authenticity_token"=>"luh7ShhQ9pWka7wmWMnG4WMQVAnKRjtAJwn0s5at8/GBDOtFjUwZEF70o8hOFOaAN+pVB592V1+egH/PDJVUVA==", "id"=>"6"}
  User Load (0.2ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT ?  [["id", 1], ["LIMIT", 1]]
  ↳ /Users/gorbunov/.rvm/gems/ruby-2.4.1/gems/activerecord-5.2.0/lib/active_record/log_subscriber.rb:98
  Question Load (0.1ms)  SELECT  "questions".* FROM "questions" WHERE (6) LIMIT ?  [["LIMIT", 1]]
  ↳ app/controllers/questions_controller.rb:86
   (0.0ms)  begin transaction
  ↳ app/controllers/questions_controller.rb:45
  Question Destroy (0.4ms)  DELETE FROM "questions" WHERE "questions"."id" = ?  [["id", 3]]
  ↳ app/controllers/questions_controller.rb:45
   (1.6ms)  commit transaction
  ↳ app/controllers/questions_controller.rb:45
Redirected to http://localhost:3000/questions
Completed 302 Found in 7ms (ActiveRecord: 2.4ms)

我想删除ID = 6的对象,但要删除ID = 3的对象

在控制器中执行销毁

def destroy
   @question = Question.find_by(params[:id])
   @question.destroy
   flash[:success] = 'Вопрос успешно удалён!'
   redirect_to questions_path
  end

链接到删除对象的助手:

<%= link_to qest, class: 'btn btn-outline-danger', method: :delete, data: {confirm: "Хорошо подумал?"} do %>

2 个答案:

答案 0 :(得分:2)

您使用find_by时没有提及。在不指定列的情况下使用时,find_by将其用作 WHERE 条件

将其更改为Question.find_by(id: params[:id])(如果找不到匹配的记录,则返回nil)或Question.find(params[:id])(如果找不到记录,则引发ActiveRecord::RecordNotFound错误)。

答案 1 :(得分:1)

这是线索。

Question Load (0.1ms)  SELECT  "questions".* FROM "questions" WHERE (6) LIMIT ?  [["LIMIT", 1]]
  ↳ app/controllers/questions_controller.rb:86

这是从@question = Question.find_by(params[:id])生成的。请注意WHERE (6)find_by可以在where子句中使用原始SQL的单个参数,也可以使用一列和一个值。您仅给了它一个参数,因此将其解释为SQL,因此也解释为WHERE (6)。这对于每一列都是正确的,因此您获得了一个随机列,在这种情况下为3,然后销毁它。

您反而想要:

@question = Question.find_by(id: params[:id])

或者更好,使用find

@question = Question.find(params[:id])

如果您要销毁它,请使用destroy on the class

Question.destroy(params[:id])