【问题标题】:Routing when using update_attribute with link_to in Rails在 Rails 中使用 update_attribute 和 link_to 时的路由
【发布时间】:2014-03-13 17:16:40
【问题描述】:

在使用 link_to 通过控制器更新属性时,我正在尝试正确路由:

查看 (@orders.each)

<%= link_to 'Cancel', controller: :orders, action: 'cancel_order', id: order.id %>

订单控制器

def cancel_order
  @order = Order.find(params[:id])
  @order.update_attribute(status: 0)
  redirect_to root_url
 end

无论我如何处理我的路线,我都会收到此错误:

No route matches {:action=>"cancel_order", :controller=>"orders", :id=>1}

请帮忙!

【问题讨论】:

  • rake routes 的输出是什么?
  • 你能发布你的 routes.rb 文件吗?

标签: ruby-on-rails ruby-on-rails-4


【解决方案1】:

routes.rb

第一种情况

resources :orders do
  member do
    get :cancel  #output path - cancel_orders/:id
  end
end

第二种情况

get 'cancel_order/:id' => 'orders#cancel_order', as: :cancel_order

输出路径:cancel_order/:id:


1 链接:&lt;%= link_to 'Cancel', cancel_orders_path(order) %&gt;

2 链接:&lt;%= link_to 'Cancel', cancel_order_path(order) %&gt;

【讨论】:

    【解决方案2】:

    我试了一下。我不确定您使用的是哪个版本的 Rails。这是我的代码 sn-p

    我的cancel_order 方法

      def cancel_order
        @order = Order.find params[:id]
        @order.update_attributes status: true
        redirect_to root_url
      end
    

    我的show.html.erb

    <%= link_to 'Cancel', cancel_order_order_path(@order), :method => :post %>
    

    我的routes.rb

      resources :orders do
        member do
          post 'cancel_order'
        end
      end
    

    还有其他方法可以实现工作路由,但这对我来说感觉更干净。如果您发布路线配置,将更容易找出您的问题。希望对您有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-08
      • 1970-01-01
      • 1970-01-01
      • 2017-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多