在 Sinatra 中删除记录

Delete Record in Sinatra

我在使用 Active Record 实现到 Sinatra 的删除路由时遇到了一些问题。这是代码详情

路线

delete '/contacts/:id' do
  @contact = Contact.find_by_id(params[:id])
  if @contact
   @contact.destroy
 else
   halt 404, "Contact not found"
 end

查看

%table.u-full-width
        %thead
          %tr
            %th Name
            %th Phone Number
            %th
        %tbody
          - @contacts.each do |contact|
            %tr
              %td= contact.name
              %td= contact.phone_number
              %td{}
                %form{:style => "margin: .75rem auto auto .25rem", :action => "/contacts/#{@contact.id}", :method => "post"}
                  %input{:name => "_method", :type => "hidden", :value => "DELETE"}/
                  %input.button#button-delete{:type => "submit", :value => "Delete"}/

堆栈错误

NoMethodError at /contacts undefined method `id' for nil:NilClass file: contacts.haml location: block (2 levels) in singleton class line: 55

难道:id没有通过我的观点?我需要在我的 table 中列出 contact.id 才能接收吗?任何帮助或文档都会很棒。

谢谢!

您的错误表明当您尝试呈现表单时您的局部变量 @contact 为 nil。

:action => "/contacts/#{@contact.id}"

当您渲染这个视图时,您是否真的将接触对象传递给上下文?

问题是你给 @contact.id:action => "/contacts/#{@contact.id}" 中不存在。

事实上,您有 @contacts,其中包含您的所有联系人,contact 是单个联系人。 @contact 为 nil

是正常的

直接换成:action => "/contacts/#{contact.id}"

如果您检查错误消息,错误与您编写 delete 操作的方式无关。您的 delete 操作看起来没有问题。错误在与您的 index 操作对应的视图文件中。

index 操作中,您可能按照以下方式做了一些事情:@contacts = Contact.all 将实例变量 @contacts 设置为联系人集合。

当您在视图中到达 - @contacts.each do |contact| 时,您将遍历联系人集合中的每个元素并在每次块为 运行 时定义一个名为 contact 的局部变量.这是您应该在此处引用的 :action => "/contacts/#{@contact.id}" 而不是 @contact

您正在尝试构建一个指向 @contacts 中每个元素的删除操作的表单,但您实际上并没有引用联系人本身,因为 @contact 是一个从未设置的实例变量。 @contact 仅在您实际发出路由到 delete 操作的请求后设置。