通过覆盖控制器操作和视图来自定义Devise Gem

时间:2014-02-23 01:05:02

标签: ruby-on-rails ruby ruby-on-rails-3 devise

在我的项目中,sign_upsign_in表单将显示在主页中,而不是显示在users/sign_upusers/sign_in中。当用户没有在电子邮件中正确输入信息时密码字段,而不是返回users/sign_up,我们只会再次显示主页。

我试图找到如何自定义路径并显示视图,但我不能。 所以我通过覆盖`registrations_controllersign_up表单来自行定制。这是我的自定义代码:

RegistrationsController :只需将responds_with更改为`redirect_to

class RegistrationsController < Devise::RegistrationsController
  def create
    build_resource(sign_up_params)

    if resource.save
      yield resource if block_given?
      if resource.active_for_authentication?
        set_flash_message :notice, :signed_up if is_flashing_format?
        sign_up(resource_name, resource)
        respond_with resource, :location => after_sign_up_path_for(resource)
      else
        set_flash_message :notice, :"signed_up_but_#{resource.inactive_message}" if is_flashing_format?
        expire_data_after_sign_in!
        respond_with resource, :location => after_inactive_sign_up_path_for(resource)
      end
    else
      clean_up_passwords resource
      redirect_to root_path, error: "Please check again"
    end
  end
end

routes.rb

devise_for :users, controllers: { registrations: "registrations" } 

* sign_up_form * (devise / registrations / new.html.haml)中: 仅将form_for resource, as: resource_name...更改为User.new:user

%h3 Sign up
= form_for User.new, :as => :user, :url => registration_path(:user) do |f|
  .form-group
    = f.email_field :email, autofocus: true, placeholder: 'Email', class: 'form-control'
  .form-group
    = f.password_field :password, placeholder: 'Password', class: 'form-control'
  .privacy
    By clicking Join Now, you argeed User Argeement InterestWeShare 's Privacy Policy and Cookie Policy.
  = f.submit "Join me in!", class: 'btn btn-primary'

我认为我的代码不好,因为我只是在控制器中稍微改变一下,但我必须自己重写动作(虽然只是复制代码 - 对最佳实践不利)。在视图中,我不知道如何以更好的方式自定义资源和resource_name。请帮忙。

0 个答案:

没有答案