从数据库中删除整个条目

时间:2019-04-13 23:01:44

标签: ruby-on-rails

我正试图在显示页面上创建一个删除按钮,以显示所选配方的数据。我的问题是,每次尝试创建删除按钮时,我都会不断收到路径错误,例如“无法找到路径recipe_path”,或者是显示

的错误
/home/robert/recipe/app/views/recipes/show.html.erb:41: syntax error, unexpected tIDENTIFIER, expecting ')' ...pend=( link_to 'Delete' recipes, method: :delete );@output_b... ... ^~~~~~~" 

如果您需要更多代码或信息,请询问。

我试图改变自己的道路,看那些有类似删除问题的人,并观看了几则有关删除红宝石的视频,但都无济于事。

<button><%= link_to 'Delete' recipes, method: :delete   
 %></button>


def destroy
   @recipes = Recipe.find(params[:id])
   @recipes.destroy
 end

对于我所做的删除按钮的某些排列,我得到了上述错误消息,或者显示了一个不起作用的按钮。

1 个答案:

答案 0 :(得分:1)

参数列表中'Delete' recipes之间缺少逗号:

<%= link_to 'Delete', recipes, method: :delete %>

解决了语法错误。但是,将<a>放在<button>标记内是无效的HTML。

  

允许的内容
     设定内容,但不得包含互动内容
     -MDN Web Docs: The Button element

只需使用CSS将常规<a>的样式设置为按钮即可,或者将create a discrete form的样式设置为button_to

<%= button_to 'Delete', recipes, method: :delete %>

由于您似乎只是四处闲逛,因此可以通过运行脚手架生成器获得如何实际编码的示例。

$ rails g scaffold recipe title:string

哪个生成:

# config/routes.rb
Rails.application.routes.draw do
  resources :recipes
  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end

# app/controllers/recipes_controller.rb
class RecipesController < ApplicationController
  before_action :set_recipe, only: [:show, :edit, :update, :destroy]

  # GET /recipes
  # GET /recipes.json
  def index
    @recipes = Recipe.all
  end

  # ...

  # DELETE /recipes/1
  # DELETE /recipes/1.json
  def destroy
    @recipe.destroy
    respond_to do |format|
      format.html { redirect_to recipes_url, notice: 'Recipe was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_recipe
      @recipe = Recipe.find(params[:id])
    end

    # ...
end

# app/views/recipes/index.html.erb
<table>
  <thead>
    <tr>
      <th colspan="3"></th>
    </tr>
  </thead>

  <tbody>
    <% @recipes.each do |recipe| %>
      <tr>
        <td><%= link_to 'Show', recipe %></td>
        <td><%= link_to 'Edit', edit_recipe_path(recipe) %></td>
        <td><%= link_to 'Destroy', recipe, method: :delete, data: { confirm: 'Are you sure?' } %></td>
      </tr>
    <% end %>
  </tbody>
</table>

请注意,在Rails中,正确的复数非常重要,因为它与整个配置方法约定有关。