Ruby-on-rails button_to :action => 'destroy' 寻找 'show'

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3763031/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 23:14:54  来源:igfitidea点击:

button_to :action => 'destroy' looks for 'show'

ruby-on-rails

提问by pedalpete

This seems incredibly similar to a question I had answered just a few days ago, but the solution then isn't working now.

这似乎与我几天前回答的一个问题非常相似,但当时的解决方案现在不起作用。

I'm building a rails app, and I am trying to have a button_to trigger a destroy in a different controller.

我正在构建一个 rails 应用程序,并且我正在尝试使用 button_to 在不同的控制器中触发销毁。

the code I have for the button is

我的按钮代码是

<%= button_to "delete", :controller => :meals, 
                           :action => 'destroy',
                           :recipe_id => recipe.id,
                           :method => :post >

when I click the delete button, i get a 'no matches for meals/3' which is the current meal_id.

当我点击删除按钮时,我得到一个“没有匹配的膳食/3”,这是当前的膳食 ID。

the destroy in the meals controller looks like this

膳食控制器中的销毁看起来像这样

  def destroy
    @meal = Meal.where("current_user.id => ? AND recipe_id => ?", current_user.id, params[:recipe_id]).first
    @meal.destroy

    respond_to do |format|
      format.html { redirect_to :controller => "user" , :action => "show" }
      format.xml  { head :ok }
    end
  end

it appears as though the button_to is completely ignoring the :action and requesting show which does not exist and shouldn't exist.

似乎 button_to 完全忽略了 :action 并请求不存在也不应该存在的节目。

回答by gertas

And how you part of routes.rb for that one looks like? Because if you use map.resources then destroy has same path as show but :method => :delete(which is virtual verb implemented by form and _method=delete param).

你如何为那一个路由的一部分看起来像?因为如果您使用 map.resources 然后 destroy 具有与 show but 相同的路径:method => :delete(这是由 form 和 _method=delete 参数实现的虚拟动词)。

Try this:

尝试这个:

<%= button_to "delete", {:controller => :meals,
      :action => 'destroy', :id => recipe.id }, :method => :delete %>

or if recipeis instance of Mealclass then

或者如果recipeMeal类的实例然后

<%= button_to "delete", @recipe, :method => :delete %>

Mind the curly brackets.

注意大括号。

回答by Sasi_Kala

I know it is way too late for an answer but hope it may help somebody(using Rails 4).

我知道现在给出答案为时已晚,但希望它可以帮助某人(使用 Rails 4)。

 <%= button_to "delete", meal_path(:id => recipe.id), :method => :delete %>