2011-03-29 66 views
2

因为,我是新来的铁轨,所以我想知道一个小功能。 我在我的rails 3应用程序中有一个报告模型(不是通过脚手架)。我通过ajax功能逐个显示报告。我想为每个报告添加一个删除链接。我也在我的控制器中创建了销毁方法。现在,当我点击特定报告的删除链接时,我不知道如何删除特定报告。 这里是我的控制器代码: -如何从模型中删除轨道中的特定帖子?

class ReportsController < ApplicationController 
    def index 
    @reports = Report.all(:order => "created_at DESC") 
    respond_to do |format| 
     format.html 
    end 
    end 

    def create 
    @report = Report.create(:description => params[:description]) 
    respond_to do |format| 
     if @report.save 
     format.html { redirect_to reports_path } 
     format.js 
     else 
     flash[:notice] = "Report failed to save." 
     format.html { redirect_to reports_path } 
     end 
    end 
    end 

    def destroy 
    @report = Report.find(params[:id]) 
    if @report.destroy 
     format.html { redirect_to reports_path } 
     format.js   
    end 
    end 
end 

你可以假设我的报告显示在Twitter的时间线格式,我想删除报告功能添加到每个报告。请帮助我。

+0

你的控制器代码看起来不错。你的视图代码是什么样的?如果它是“ajax功能”,则可能必须编写一些JavaScript,从视图中删除已删除的记录。 – Mischa 2011-03-29 12:57:23

+0

对不起,我有多个reports_path,这是不正确的,它应该是report_path作为mischa提到。 – McStretch 2011-03-29 13:30:37

回答

2

在您的视图中,您将添加一个链接,按钮等,以将删除操作发送回服务器。

使用link_to例如:

link_to("Destroy", report_path(report), :method => :delete, :confirm => "Are you sure?")

你可以做同样的button_to

更新:

对不起,我错过了AJAX提(感谢杰弗里W.)。

如果您想通过AJAX发送删除,您还需要添加:remote => true

+0

由于这是一个ajax调用,请确保您也删除与数据库中的条目对应的html。如果你不会;它会尝试删除不再存在的记录。只是说:-) – 2011-03-29 13:02:45

+0

@Jeffrey,感谢提到AJAX,我错过了OP的问题。我不认为他需要处理从DOM删除记录,如果这就是你的意思。我前几天刚刚这样做了,而且我很确定内置的rails助手为我处理了它。 – McStretch 2011-03-29 13:10:09

+0

嗨,我接受你的答案McStretch先生,我想你说什么,但现在的问题是,当我删除点击链接,它说 行动“秀”不能为ReportsController找到未知的动作。 – Metal 2011-03-29 13:17:38