Rails - 添加"删除"按钮到用户时间表

时间:2015-11-09 01:16:20

标签: ruby-on-rails-4

您好我有一个rails应用程序,其中用户可以拥有一对多关系的时间表。

当我添加此

<%= link_to "delete", user, method: :delete,
                data: { confirm: "You sure?" } %>

到_user.html它会呈现删除链接,删除用户没问题

但是当我添加这个

<%= link_to "delete", timetable, method: :delete,
                    data: { confirm: "You sure?" } %>

到_timetable.html.erb会抛出错误

ActionController::RoutingError (No route matches [DELETE] "/timetable.4"):

My Routes.rb

  get 'password_resets/new'
  get 'password_resets/edit'
  root 'static_pages#home'
  get 'help' => 'static_pages#help'
  get 'about' => 'static_pages#about'
  get 'contact' => 'static_pages#contact'
  get 'timetable' => 'timetables#new'
  get 'signup' => 'users#new'
  get 'mobile' => 'users#mobile'
  get 'login' => 'sessions#new'
  post 'login' => 'sessions#create'
  delete 'logout' => 'sessions#destroy'


  resources :account_activations, only: [:edit]
  resources :password_resets, only: [:new, :create, :edit, :update]
  resources :timetables
  resources :users
  resources :projects

时间表控制器

 class TimetablesController < ApplicationController

  before_action :logged_in_user, only: [:create, :destroy]
  before_action :correct_user,   only: :destroy

  def index
    @timetables = current_user.timetables.find(current_user)
  end

  def new
    @user = User.find(current_user)
    @timetable = Timetable.new
    @timetables = @user.timetables.paginate(page: params[:page], per_page: 1)
  end

  def feed
    Timetable.where("user_id = ?", id)
  end

  def show
    @feed_items3 = current_user.feed.paginate(page: params[:page])
    @timetable = current_user.timetables.find(params[:id])
  end

  def create
    @timetable = Timetable.new(timetable_params)
    @user = User.find(current_user)

    if current_user.timetables.create(timetable_params)
      flash[:success] = "Timetable created!"
      redirect_to timetable_path
    else
      flash[:success] = "Timetable not created!"
      redirect_to timetable_path
    end
  end

  def destroy
    @timetable = Timetable.find(params[:id])
    @timetable.destroy
    redirect_to timetables_path, notice:  "The timetable #{@timetable.name} has been deleted."
  end

  private
  def timetable_params
    params.require(:timetable).permit(:name, :attachment, :id)
  end

  def correct_user
    @project = current_user.projects.find_by(id: params[:id])
    redirect_to root_url if @project.nil?
  end

end

1 个答案:

答案 0 :(得分:1)

如果没有看到你的控制器,很难确定,但我会看几个方面:

指定路径&amp;要删除的时间表对象:

 <%= link_to "Delete Timetable", timetable_path(timetable), :method => :delete %>

确保时间表的销毁操作位于timetable_controller

关于您的routes.rb文件我不知道您为什么需要:

get 'timetable' => 'timetables#new'

然后

resources :timetables

这是重复 - 为什么不尝试只使用&#39; (根据您的喜好编辑):

resources :timetables, only: [:index, :new, :create, :destroy]