Rails添加了新的视图来设计
我安装了devise之后用这个命令生成了视图
rails generate devise:views
我覆盖了注册控制器
class RegistrationsController < Devise::RegistrationsController def sign_up2 end end
并更新routes.rb
devise_for :users, :controllers => { :registrations => "registrations" }
我期待看到一个新的路线/视图
/users/sign_up2
但我没有看到它和这里的路线设计
new_user_session GET /users/sign_in(.:format) devise/sessions#new user_session POST /users/sign_in(.:format) devise/sessions#create destroy_user_session DELETE /users/sign_out(.:format) devise/sessions#destroy user_password POST /users/password(.:format) devise/passwords#create new_user_password GET /users/password/new(.:format) devise/passwords#new edit_user_password GET /users/password/edit(.:format) devise/passwords#edit PATCH /users/password(.:format) devise/passwords#update PUT /users/password(.:format) devise/passwords#update cancel_user_registration GET /users/cancel(.:format) registrations#cancel user_registration POST /users(.:format) registrations#create new_user_registration GET /users/sign_up(.:format) registrations#new edit_user_registration GET /users/edit(.:format) registrations#edit PATCH /users(.:format) registrations#update PUT /users(.:format) registrations#update DELETE /users(.:format) registrations#destroy
但我想要一个新的观点和路线
更新 :加载视图时出现问题
First argument in form cannot contain nil or be empty
在这一行
resource_name,:html => { :class => "form-horizontal col-sm-12",:role=>"form"}, :url => user_registration_path(resource_name)) do |f| %>
调用devise_scope
块并在以下内容中声明自定义路由:
devise_for :users, :controllers => { :registrations => "registrations" } devise_scope :user do get "users/sign_up2"=> "users/registrations#sign_up2", :as => "sign_up2_registration" end
文档中有关配置路由的部分提供了devise_scope
的以下说明:
如果您需要更深入的自定义,例如除了“/ users / sign_in”之外还允许“/ sign_in”,您需要做的就是正常创建路由并将它们包装在路由器中的devise_scope块中
以前,Devise允许将自定义路由作为块传递给devise_for
,但此行为已被弃用 。
更新 :
要解决First argument in form cannot contain nil or be empty
的First argument in form cannot contain nil or be empty
错误,您需要确保自定义sign_up2
操作正确设置resource
变量。 假设您想模仿registrations/new
操作,您可以执行类似于以下操作的操作:
def sign_up2 build_resource({}) respond_with self.resource end
这可以确保视图中的resource
变量不是nil
并且不会抛出您当前正在目击的exception。
或者 ,根据您尝试显示的行为,您可以在自定义控制器操作中设置自己的实例变量,然后将其作为资源传递给form_for
标记:
# app/controllers/users/registrations_controller.rb def sign_up_2 @new_registrant = Registrant.new end # app/views/users/sign_up2.html.erb <%= form_for(@new_registrant, :as => resource_name,:html => { :class => "form-horizontal col-sm-12",:role=>"form"}, :url => user_registration_path(resource_name)) do |f| %>
但是 ,如果您遵循这种方法,您应该考虑为什么需要将其转换为Devise。 默认情况下,Devise通过build_resource
函数分配resource
变量。 如果您要覆盖/绕过此函数,您应该考虑从Devise中抽象出整个function,因为您完全绕过了它的默认行为。