使用ruby on rails在单击按钮上从数据库中删除记录

时间:2014-04-23 11:40:40

标签: ruby-on-rails ruby

我正在研究一种方法,当用户按下"删除按钮" 问题是,当我点击该按钮时,我想要删除的包将从网站中删除,但是当我检查数据库时,我发现了该记录。

控制器:

def deletepackage(user_id,package_id)
  @package=Packages.find(:all, :condition=>{:id => package_id}, 
                                           :condition => {:sender_Id => user_id})
    if (@package!=nil && req.receivedByCarrier==false)
        @package.destroy
    elsif (@package!=nil && req.receivedByCarrier==true)
        @package.destroy
    end
    return;
  end

  def delete
    deletepackage(1,1)
    package.destroy
    redirect_to(:action => 'show') 
  end

  def show
    @create_package=Packages.find(params[:id ])
  end

Show.html.erb:

 <%=form_for(:package,:url{:action=>'create_packages/delete',
                             :id=>@create_package.id})do |f| %>
   <p>Are you sure you want to delete this package?</p>
   <%= f.submit "Delete" %>

1 个答案:

答案 0 :(得分:2)

<强> Show.html.erb:

<%= link_to 'Delete', controller: 'your_controller_name', action: 'destroy', id: @package.id, method: :delete %>

<强>控制器:

def show
  @package = Packages.find(params[:id])
end

def destroy
  Packages.find_by(id: params[:id], sender_Id: 1).destroy
  redirect_to :index
end

你无法从destroy重定向到'show'动作,因为没有要显示的包(包被破坏)。

<强> P.S:

我认为,您需要学习一些rails教程,例如Michael Hartl's Tutorial