Rails 3 中的自定义操作 [英] custom action in rails 3

查看:33
本文介绍了Rails 3 中的自定义操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to make a simple link that will toggle my "status" attribute in my model from "pending" to "active". For example, when I first create a user, I set the status to "pending". Then when I show the list of users, I add a button that should change that user's status to "active". I tried this via a custom action (is this a good approach?) but I'm having trouble with the auto-generated named route.

在我的用户 index.html.haml 中:button_to手动激活",activate_user_path

in my user index.html.haml: button_to "Manually Activate", activate_user_path

在 routes.rb 中:

in routes.rb:

resources :users do
  get :activate, :on => :member

在 users_controller.rb 中:

in users_controller.rb:

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

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

this seems to work when I go to say, /users/1/activate, as the status will update. However, the /users page doesn't show and gives me error:

ActionController::RoutingError in Users#index
No route matches {:action=>"activate", :controller=>"users"}

即,我在视图中指定的 activate_user_path 有问题.(但是,如果我使用另一个未在 routes.rb 中指定的命名路由样式路径来测试它,我会得到

ie, it is having a problem with the activate_user_path I specified in my view. (However if I use another named-routes-style path that I haven't specified in my routes.rb to test it out, I get

NameError in Users#index
undefined local variable or method `blahblah_user_url' for #<#<Class:0x00000102bd5d50>:0x00000102bb9588>

所以它似乎知道它在 routes.rb 中,但还有其他错误吗?我真的是 Rails 的新手,非常感谢您的帮助!谢谢!

so it seems that it knows it's in the routes.rb but something else is wrong? I'm really new to rails and would appreciate the help! thanks!

推荐答案

您的链接应如下所示:

button_to "Manually Activate", activate_user_path(@user)

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

You need to add what user you want to activate.

这篇关于Rails 3 中的自定义操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆