ruby-on-rails - 如何在一个 Controller 中创建两个更新操作

标签 ruby-on-rails ruby-on-rails-4 routes

因此,很自然地,每当有人在 routes.rb 文件中指定资源时,例如......

资源:用户

...该资源生成 7 个示例操作...

users#new     (GET)
users#create  (POST)
users#show    (GET)
users#edit    (GET)
users#update  (PATCH/PUT)
users#destroy (DELETE)

问题:

现在,我想要实现但不能做的是向我的 Controller 文件添加额外的更新操作,以便它能够更新不同的参数。与第一个更新操作不同。

在我的 users_controller.rb 文件中,我有...

class UsersController < ApplicationController
  .
  .
  .
  # First update action
  def update
    @user = User.find(params[:id])
    if @user.update_attributes(user_params)
      flash[:success] = "Profile updated"
      redirect_to @user
    else
      render 'edit'
    end
  end

  # Second update action
  def update_number_two
    @user = User.find(params[:id])
    if @user.update_attributes(user_other_params)
      flash[:success] = "Other params updated"
      redirect_to @user
    else
      render 'other_view' 
    end
  end

  private

    # Params for the first action
    def user_params
      params.require(:user).permit(:name, :email, :password, :password_confirmation)
    end

    # Params for the second action
    def user_other_params
      params.require(:user).permit(:other_param)
    end
end

所以我遇到的问题是,为了使上面的代码正常工作,我需要将自定义更新操作路由添加到我的routes.rb 文件中。

我尝试将其添加到我的 route ...

patch 'users#update_number_two'
put   'users#update_number_two'

...还有其他一些东西,但没有任何效果。

如果有人可以告诉我应该在routes.rb 文件中添加哪些内容,或者只是将我推向正确的方向,我们将不胜感激您的帮助。

最佳答案

为了向特定资源添加另一个操作,您需要使用member:

2.10 Adding More RESTful Actions

You are not limited to the seven routes that RESTful routing creates by default. If you like, you may add additional routes that apply to the collection or individual members of the collection.

resources :users do
  member do
    patch :update_number_two
    put :update_number_two
  end
end

然后,当您想要更新时,请选择表单的不同操作(update_number_two_user_path || /users/:id/update_number_two)

update_number_two_user PATCH  /users/:id/update_number_two(.:format) users#update_number_two
                       PUT    /users/:id/update_number_two(.:format) users#update_number_two

运行rake:routes查看结果

更多信息:Adding More RESTful Actions

关于ruby-on-rails - 如何在一个 Controller 中创建两个更新操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31462203/

相关文章:

mysql - 应为此 MySQL 查询创建哪些索引

ruby-on-rails - Assets 预编译错误:未初始化的常量 Mongo::Logging

ruby-on-rails - Rails 命名范围不适用于关联

javascript - 添加 anchor 到 AngularJS State

angular - 如何在没有插件的情况下平滑滚动到 Angular 4 中的页面 anchor ?

ruby-on-rails - RSpec:通过正则表达式匹配字符串数组

ruby-on-rails - 是否可以从 Rails 3 中的 Controller 调用使用 "content_tag"的方法?

ruby - 在没有 attr_accessible 的 Rails 4 中 self 记录 ActiveRecord 类文件

ruby-on-rails - Model.where(...).first 属性不是 nil 但显示 nil

regex - Symfony2 如何在路由正则表达式中允许带破折号的 slug?