我最初在Routing Errors on attempts to delete all records in a table using Rails 4 through a link_to发布了路由错误,并且已经解决了。
现在我遇到了传递“id = remove_all”的问题。我正在使用Rails 4,并尝试使用link_to帮助程序删除所有评估。相关代码如下:
的routes.rb
resources :assessments do
collection do
delete :remove_all
end
end
评估index.html.erb
<p>To delete all assessments in one swoop, click <%= link_to 'Remove ALL Assessments', remove_all_assessments_path, method: :destroy, data: { confirm: 'Are you sure?' } %>
assessments_controller.rb
def remove_all
@assessments = Assessment.all
@assessments.each do |assessment|
assessment.destroy(assessment.id)
end
flash[:notice] = "All assessments have been deleted."
redirect_to assessments_url
end
我运行rake路线和
Prefix Verb URI Pattern Controller#Action
remove_all_assessments DELETE /assessments/remove_all(.:format) assessments#remove_all
为链接生成的HTML源代码:
<p>To delete all assessments in one swoop, click <a data-confirm="Are you sure?" data-method="destroy" href="/assessments/remove_all" rel="nofollow">Remove ALL Assessments</a>
当我点击“删除所有评估”链接时,我希望在AssessmentsController中运行remove_all操作,并删除@assessments中的所有评估,然后将我重定向到assessment_url。但是,当我点击“删除所有评估”链接时,我会被带到网址:http://localhost:3000/assessments/remove_all
ActiveRecord::RecordNotFound in AssessmentsController#destroy
Couldn't find Assessment with id=remove_all
# Use callbacks to share common setup or constraints between actions.
def set_assessment
@assessment = Assessment.find(params[:id])
end
日志显示:
Started DELETE "/assessments/remove_all" for 127.0.0.1 at 2014-01-31 15:41:41 -0500
Processing by AssessmentsController#destroy as HTML
Parameters: {"authenticity_token"=>"fooBarBaz=", "id"=>"remove_all"}
如何使用Delete动词将@assessments的集合传递给remove_all操作?这可能吗?
答案 0 :(得分:0)
是因为
resources :assessments
已经有破坏的路线
比如/assessment/:id with method :delete
所以你的remove_all_assessments_path
会在你的routes.rb文件中找到它的第一个url bcoz
要解决您的问题,您必须执行以下操作: -
resources :assessments, except: [:destroy] do
collection do
delete :remove_all
end
end
或在其上方定义您的remove_all_assessments网址。
像
match "/assessments/remove_all", to: "assessments#remove_all", via: [:delete], as: :remove_all_assessments
resources :assessments do
collection do
delete :remove_all
end
end