TagsController#create

时间:2018-11-11 01:08:54

标签: ruby-on-rails controller routes destroy

我正在尝试从索引页触发针对附加到多个记录的标签的销毁操作。但是,当触发操作时,我在创建操作中遇到了以上错误。调用create动作时不会发生该错误。我的代码如下所示。

标签控制器

class TagsController < ApplicationController
before_action :require_user, only: [:edit, :update, :destroy]
before_action :set_search

def new
    @tag = Tag.new
end

def create
    tag = Tag.create(tag_params)
    if tag.save
        redirect_to tags_path
    else
        redirect_to sign_up_path
    end
end

def destroy
    @tag = Tag.find(params[:tag_id])
    @tag.destroy

    redirect_to tags_path
end

private
    def tag_params
        params.require(:tag).permit(:name)
    end
end

路线

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

  resources :users

  get 'recipes' => 'recipes#index'
  get 'recipes/:id' => 'recipes#show'

  get 'signup' => 'users#new'

  get 'tags' => 'tags#index'
  get 'new_tags' => 'tags#new'
  post 'tags' => 'tags#create'
  delete 'tags' => 'tags#destroy'

  get 'login' => 'sessions#new'
  post 'login' => 'sessions#create'
  delete 'logout' => 'sessions#destroy'

  root 'recipes#index'

end

索引

  <%= link_to 'New Tag', new_tags_path(@tag) %> 

  <% Tag.find_each do |tag| %>
    <%= tag.name %>
    <%= link_to 'Delete Tag', @tag,
              method: :destroy,
              data: { confirm: 'Are you sure?' } %>
  <% end %>

2 个答案:

答案 0 :(得分:0)

这条路线:

delete 'tags' => 'tags#destroy'

表示没有ID参数的“ / tags”。

您必须告诉路由器,您希望将一部分网址用作:tag_id

delete 'tags/:tag_id' => 'tags#destroy'

无论如何,我建议您坚持使用Rails约定并只使用

resources :tags

并在控制器上

@tag = Tag.find(params[:id])

我不确定您为什么要手动设置路由,如果您不熟悉Rails,请阅读以下链接:https://guides.rubyonrails.org/routing.html

你甚至有这行

get 'recipes' => 'recipes#index'
get 'recipes/:id' => 'recipes#show'

这是不必要的,因为resources :recipes已经创建了它们。

答案 1 :(得分:0)

该错误源自视图中“链接至”语句中的多个问题。应该写的链接在下面...

<%= link_to 'Delete Tag', tag_path(tag),
          method: :delete,
          data: { confirm: 'Are you sure?' } %>