【发布时间】:2014-07-20 15:45:48
【问题描述】:
我是 Rails 新手,正在尝试实现用户注册页面(在 CRUD 中创建)。除了提交按钮之外,我还想要一个取消按钮,以便用户可以单击它并返回索引页面。我已完成以下操作,但取消按钮仍会注册用户。
哈姆代码(new.html.haml):
=form_tag users_path, :method => :post do
%p= label :user, :username, "User Name"
%p= text_field :user, :username
... (other information)
= button_tag "Submit", :type => 'submit'
= button_tag "Cancel", :type => 'cancel'
Rails 代码(users_controller.rb):
class UsersController < ApplicationController
before_filter :check_for_cancel, :only => [:create, :update]
def create
vals = params[:user]
if(User.exists(vals[:username]))
flash[:warning] = "#{vals[:username]} already exists! Please try a new one. "
else
vals[:create_date] = DateTime.current
vals.except!(:confirm_password)
@user = User.create(vals, :without_protection => :true)
unless @user==nil
flash[:notice] = "#{vals[:username]} has been registered. "
else
flash[:warning] = "#{vals[:username]} has not been registered successfully. "
end
end
redirect_to users_path
end
...(other CRUD methods)
def check_for_cancel
if(params[:commit]=="cancel")
flash[:notice] = "Registration is cancelled. "
redirect_to users_path
end
end
end
谢谢。
【问题讨论】:
-
在您的
check_for_cancel方法中,尝试使用redirect_to users_url。本质上,尝试使用_url而不是_path后缀。 -
@theSshow 它不起作用。实际上,当我故意使网站崩溃并检查参数的调试信息时,我什至看不到 :commit 作为键。那部分正确吗?
-
实际上,合法的按钮类型只有
submit、reset和button(developer.mozilla.org/en-US/docs/Web/HTML/Element/button)。cancel不是type属性的有效值。也许您最好只创建一个链接并设置一个按钮的样式,如下所示:stackoverflow.com/questions/18407832/…
标签: ruby-on-rails ruby haml crud