【问题标题】:Rails Haml form url parameter - how to make html form use the desired rails routeRails Haml 表单 url 参数 - 如何使 html 表单使用所需的 rails 路由
【发布时间】:2013-02-27 16:04:33
【问题描述】:

使用 HAML 代码:

%form{:action => "activate_foobar", :method => :post, :controller => "foobar", :url => activate_foobar_foobar_index_path}
%input{:type => "submit", :value => "Activate"}

提交按钮指向

No route matches "/activate_foobar"

而不是“/foobar/activate_foobar”。好像看不懂url参数。


详情

在 foobar 的索引页面上,有一个表单,我正在尝试将其发布到 foobar_controller 的方法 activate_foobar。 Foobar 没有模型,因为没有这样的对象——它只是 Widget 的一个特殊属性。 (Widget 有一个模型,一个方法 .activate_foobar)

activate_foobar_foobar_index 在路由中定义为:

resources :foobar, :only => [:index] do
  collection do
    post :activate_foobar
  end
end

:用 rake 确认:路由为:

activate_foobar_foobar_index POST     /foobar/activate_foobar(.:format)   {:action=>"activate_foobar", :controller=>"foobar"}

:正如预期的那样。

此外,用一个简单的实验:

=link_to "Activate", activate_foobar_foobar_index_path, {:method => :post}

:成功路由到/foobar/activate_foobar

在使用表单的范围内(而不是使用 simple_form_for 或其他基于模型的解决方案),您如何更正路径“foobar/activate_foobar”?

来源: 我正在关注http://guides.rubyonrails.org/routing.html“添加更多 RESTful 操作”和http://www.w3schools.com/html/html_forms.asp,试图了解如何将表单引导到正确控制器的正确方法。

【问题讨论】:

    标签: ruby-on-rails haml forms


    【解决方案1】:

    就像你说的那样,它将表单发送到 /activate_foobar,由于某种原因(可能是 haml 错误),它不采用 :controller 参数来解决这个问题

    :action => 'foobar/activate_foobar'
    

    但您必须小心,因为它采用相对路径而不是绝对路径。因此,如果您不想处理该问题,我建议您更改为 rails form helper

    = form_tag(activate_foobar_foobar_index_path, :method => :post) do
    

    【讨论】:

    • 无论有无控制器参数,显式设置相对路由都会导致立即注销。 Form_tag 正是我所需要的!谢谢!
    【解决方案2】:

    因为 activate_foobar 嵌套在 foobar 下,你尝试过吗

     :url => activate_foobar_foobar_index_path(@foobar) 
    

    你需要告诉 rails 在哪里寻找特定的 foobar 来激活 foobar。

    希望对你有帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-06
      • 1970-01-01
      • 1970-01-01
      • 2012-06-17
      • 1970-01-01
      • 2012-02-10
      相关资源
      最近更新 更多