【问题标题】:How can I use a method action like the 'update', 'create' or 'destroy' actions (from scaffold)?如何使用方法操作,如“更新”、“创建”或“销毁”操作(来自脚手架)?
【发布时间】:2011-05-27 18:32:14
【问题描述】:

我对@9​​87654321@ 进行了适当的更改:

现在在 'app/controllers/users_controller.rb' 我有这个代码:

def reset
    respond_to do |format|
        format.html # reset.html.erb
    end
end

def send_reset
    respond_to do |format|
        if @user.errors.empty?
            ...
        else
            format.html { render :action => 'reset' }
        end
    end
end

现在在 'config/routes.rb' 我有这个代码:

  resources :users do
    collection do
      get 'reset'
      post 'reset'
      get 'send_reset'
      post 'send_reset'
    end
  end

如果我提交与changes相关的表单('app/views/users/reset.html.erb')

<%= form_tag( send_reset_users_path, :method => :post ) do %>
    <%= text_field_tag :email %>
    <%= submit_tag("Send") %>
<% end %> 

浏览器 URL 变为 '.../users/send_reset' 但我想要 '.../users/reset' (我认为问题出在'format.html { render :action => 'reset' }' 代码不能正确渲染动作)或者可能是路由。

简而言之,我的目标是使用“send_reset”操作,例如,“更新”、“创建”或“销毁”操作(来自脚手架),在我的情况下是不创建'app/views/users/send_reset.html.erb' 文件,但只是调用操作方法来处理我的问题。我该怎么做?

【问题讨论】:

    标签: ruby-on-rails forms controller action routes


    【解决方案1】:

    默认的 Rails URL 方案是

    :host/:controller/:action/:id
    

    重命名你的控制器动作

    def send_reset
    end
    

    def reset
    end
    

    并重命名视图和路由以匹配此更改。

    但是,您已经在 get 和 send_reset 中使用了 reset 和 post,但是如果您请求页面或发送表单 POST,您希望它们相同,只是做不同的事情。

    def reset
       case request.method
       when :post
           # send them an email
           # redirect_to :somewhere_else
       else # :get, :put, :delete
           # render the view with the recovery form
       end
    end
    

    【讨论】:

    • 重命名我将在“app/controllers/users_controller.rb”中有两个同名的操作方法。这是正确的方法吗?
    • 我忽略了这一点。因此,您想要的是基于 HTTP 请求类型的相同操作的不同功能。我会更正我的答案。
    • “所以你想要的是基于 HTTP 请求的相同操作的不同功能”:这是 RoR 用于路由“更新”、“创建”或“销毁”操作的常用方式(来自脚手架)?
    • Rails 3 way 对它皱眉。这是早期的 Rails 2 主义。更好的 Rails 3 方法可能是通过 ajax 将表单提交到 send_reset,而用户永远看不到它。
    • 我试过你的代码(case request.method ...),但是当我提交表单时,它总是通过'else'条件,即使我设置了':method =>:post '。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多