【问题标题】:Rails, trouble in a form trying to use the put http methodRails,表单中的麻烦,尝试使用 put http 方法
【发布时间】:2009-07-20 00:54:42
【问题描述】:
<% form_ tag user_path(@user), :method => :put do %>

这是我的表单,所以我希望它访问我的 UsersController 的更新方法,我设置了 map.resources :users ,并生成了 RESTful 路径:

users     GET    /users(.:format)          {:action=>"index", :controller=>"users"}          
          POST   /users(.:format)          {:action=>"create",:controller=>"users"}
new_ user GET    /users/new(.:format)      {:action=>"new", :controller=>"users"}
edit_user GET    /users/:id/edit(.:format) {:action=>"edit", :controller=>"users"}
user      GET    /users/:id(.:format)      {:action=>"show", :controller=>"users"}
          PUT    /users/:id(.:format)      {:action=>"update", :controller=>"users"}
          DELETE /users/:id(.:format)      {:action=>"destroy", :controller=>"users"}

所以我尝试使用 PUT HTTP 方法发送到 user_path(@user) 并返回:

Unknown action

No action responded to 1. Actions: create, destroy, edit, index, logged?, new, show and update

显然我不知道如何进行这项工作,所以在此先感谢。

【问题讨论】:

    标签: ruby-on-rails ruby forms rest


    【解决方案1】:

    如果您使用的是 RESTful 资源(并且应该使用),请尝试使用 form_for 而不是 form_tag ... 完整设置如下:

    <% form_for :user, @user, :url=>user_path(@user), :html=>{:method=>:put} do |f| %>
    
      #this scopes the form elements to the @user object, eg.
      <%= f.text_field :first_name %>
    
    <% end %>
    

    查看API docs 了解更多信息。

    【讨论】:

      【解决方案2】:

      回答为时已晚,但请查看http://guides.rubyonrails.org/form_helpers.html#how-do-forms-with-put-or-delete-methods-work

      并非所有浏览器都支持 PUT,因此您可以使用带有隐藏输入的 POST,说明该方法是 PUT

      【讨论】:

        【解决方案3】:

        只是在黑暗中拍摄,但你试过吗?

        <% form_tag :url=>user_path(@user), :html=>{:method=>:put} do %>
        

        【讨论】:

        【解决方案4】:

        您是否重新启动了服务器?如果我在服务器运行时更​​新它,我的 routes.rb 永远不会正确重新加载。

        【讨论】:

          【解决方案5】:

          我在尝试使用无表模型时遇到了这个确切的问题 (Rails model without database)。

          在快速研究了 actionpack 的 form_helper.rb 之后,我找到了一个解决方案。将此添加到您的模型中:

          def new_record?; false; end
          

          在我的例子中,我的模型总是从头开始构建的,因此有必要“欺骗”Rails 将其视为现有对象,从而执行 PUT 而不是 POST。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多