Rails按钮调用控制器方法,不重定向

问题描述 投票:0回答:2

我试图从Rails视图中的按钮调用控制器中的方法。我在这里关注了其他一些问题,并且到了这一点。

routes.rb

namespace :processing do
  resources :applications do
    stuff
    post :test, :to => 'applications#test', :on => :member
  end
end

控制器方法简称为test。这是控制器的相关部分:

def test
  @application = Application.find_by(record_id: params[:id])
  puts 'THIS IS A TEST'
end

最后,我在.erb文件中使用此代码调用路由:

<%= button_to 'Send to Processing', 
      test_processing_application_path(record_id), 
      method: :post, form_class: 'btn btn-danger' %>

按钮呈现正确,似乎遵循正确的路线。但是,我的问题是按钮尝试重定向并呈现不存在的路由/processing/applications/715707082/test并导致问题。

如何让这个按钮不重定向/渲染一些东西,而只是从当前页面调用方法?如果它复制了现有问题,请随时链接我相关的帖子或关闭它。

ruby-on-rails ruby erb rails-routing
2个回答
1
投票

routes.rb文件中的路由确实定义了

test_processing_application_path作为路径的POST

/processing/applications/:id/test(.:format)

期望在控制器中实现

processing/applications#test -

这是app/controllers/processing/applications_controller.rb中的一个文件,它定义了一个控制器,如:

module Processing
  class Applications < ApplicationController
    def test
      # your code here
    end
  end
end

0
投票

您应该使用action而远程true将不会使用方法,而是会触发ajax请求并阻止您重定向。然后创建一个test.js.erb文件,用于处理ajax请求以更新将在操作调用后执行的DOM。

<%= button_to 'Send to Processing',test_processing_application_path(record_id), 
action: :test, form_class: 'btn btn-danger', :remote=>true %>

希望这会有所帮助。

干杯。

© www.soinside.com 2019 - 2024. All rights reserved.