Rails:相同路径的GET和POST路由导致ArgumentError

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

当我访问/contact时,我得到:

ArgumentError (wrong number of arguments (given 1, expected 0)):
app/controllers/contact_controller.rb:6:in `send'

以下是config/routes.rb的内容:

Rails.application.routes.draw do
  root to: 'home#index'  
  get  'contact', to: 'contact#index'
  post 'contact', to: 'contact#send'
end

是否包括getpost相同路径的路线会导致get不被使用? ContactControllerindexsend有空洞的行动,但index似乎被忽略了。

ruby-on-rails ruby-on-rails-5
1个回答
4
投票

我认为问题是Rails使用Object#send按名称调用控制器方法,但你有自己的send方法。在Rails路由系统内部,它知道它应该将GET /contact路由到一个名为字符串'index'的方法;代码看起来像这样:

controller_instance = an_instance_of_ContactController_from_somewhere
controller_method   = 'index' # This string will be extracted from the `get 'contact', to: '...'` call in routes.rb

controller_instance.send(controller_method)

你应该能够将你的send方法重命名为其他东西,更新你的routes.rb,一切都应该没问题;例如:

post 'contact', to: 'contact#send_message'

然后在contact_controller.rb

def send_message
  #...
end
© www.soinside.com 2019 - 2024. All rights reserved.