rails 3中的自定义操作

but*_*bat 8 ruby-on-rails

我正在尝试创建一个简单的链接,将我的模型中的"status"属性从"pending"切换为"active".例如,当我第一次创建用户时,我将状态设置为"pending".然后,当我显示用户列表时,我添加了一个按钮,该按钮应该将该用户的状态更改为"活动".我通过自定义操作尝试了这个(这是一个很好的方法吗?)但是我遇到了自动生成的命名路由问题.

在我的用户index.html.haml中: button_to "Manually Activate", activate_user_path

在routes.rb中:

resources :users do
  get :activate, :on => :member
Run Code Online (Sandbox Code Playgroud)

在users_controller.rb中:

 def activate
    @user = User.find(params[:id])
    @user.update_attribute(:status, 'Active')
    redirect_to @user
  end
Run Code Online (Sandbox Code Playgroud)

当我去说/ users/1/activate时,这似乎有效,因为状态会更新.但是,/ users页面没有显示并给我错误:

ActionController::RoutingError in Users#index
No route matches {:action=>"activate", :controller=>"users"}
Run Code Online (Sandbox Code Playgroud)

即,我在视图中指定的activate_user_path出现问题.(但是如果我使用另一个我没有在routes.rb中指定的命名路由风格的路径来测试它,我得到了

NameError in Users#index
undefined local variable or method `blahblah_user_url' for #<#<Class:0x00000102bd5d50>:0x00000102bb9588>
Run Code Online (Sandbox Code Playgroud)

所以它似乎知道它在routes.rb中,但其他东西是错的?我是铁杆的新手,非常感谢你的帮助!谢谢!

kle*_*lew 9

您的链接应如下所示:

button_to "Manually Activate", activate_user_path(@user)
Run Code Online (Sandbox Code Playgroud)

您需要添加要激活的用户.


Adi*_*ghi 6

我可以看到一些问题.首先,您不应使用GET请求更新数据库.其次button_to将为您提供一个就地表单,单击该表单将POST到您的应用程序.第三,您设置路由的方式,您需要在路径中提供用户(您已经通过在浏览器中形成URL来测试它).

rake routes
Run Code Online (Sandbox Code Playgroud)

在命令提示符下查看路由的外观以及可用于生成这些路由的名称.

我怀疑你需要使用

button_to "Manually Activate", activate_user_path(user)
Run Code Online (Sandbox Code Playgroud)

(用户或@user或其他任何用户对象).在您的button_to调用并将路径文件中的"get"更改为"post".

resources :users do
  member do
    post :activate
  end
end
Run Code Online (Sandbox Code Playgroud)