2016-10-08 3 views
0

Я пытаюсь использовать Devise Gem в своем приложении rails для аутентификации, когда пользователь подписывается. Но когда я иду на консоль rails, чтобы проверить таблицу User, у нее нет нового пользователя, созданного в базе данных. Я попытался переопределить контроллер регистрации Devise с помощью моего контроллера регистрации, но не повезло. Контроллер регистрации, похоже, не устанавливает метод создания, чтобы его можно было создать в базе данных. Может ли кто-нибудь предложить какую-либо помощь, где я ошибаюсь?Невозможно получить новую регистрацию пользователя для создания пользователя в базе данных с помощью Devise Gem

Что показывает в журналах сервера после того, как пользователь подпишется:

работы GET «/ пользователи/sign_up utf8 =% E2% 9C% 93 & authenticity_token = ruu1To891VYxDpsZlU4HjeAatrsX% 2BQXcjj0WVpFexExAaEuKxQEDhrNl8GNqeu30lcaiwJFED7H40cmqXH% 2FxpA% 3D% 3D & пользователь% 5Bemail% 5D = fake.email% 40gmail.com & пользователь% 5Bpassword% 5D = [FILTERED] & commit = Sign + up "for :: 1 at 2016-10-08 11:14:49 - 0500 Обработка Devise :: RegistrationsController # new как HTML Параметры: {"utf8" => "✓", "authenticity_tok en "=>" ruu1To891VYxDpsZlU4HjeAatrsX + QXcjj0WVpFexExAaEuKxQEDhrNl8GNqeu30lcaiwJFED7H40cmqXH/xpA == "," user "=> {" email "=>" [email protected] "," password "=>" [FILTERED] "}," commit " => "Зарегистрироваться"} Оказываемые Разрабатывают/регистрация/new.html.erb в макетах/приложений (3.6ms)

страницу регистрации new.html.erb:

<!DOCTYPE html> 
<!--[if IE 8]> <html lang="en" class="ie8"> <![endif]--> 
<!--[if IE 9]> <html lang="en" class="ie9"> <![endif]--> 
<!--[if !IE]><!--> <html lang="en"> <!--<![endif]--> 
<head> 
    <title>Sign Up</title> 

</head> 

    <body class="signup-page access-page has-full-screen-bg"> 
    <div class="upper-wrapper"> 
    <!-- Header --> 
    <!-- ******Signup Section****** --> 
    <section class="signup-section access-section section"> 
     <div class="container"> 
      <div class="row"> 
       <div class="form-box col-md-8 col-sm-12 col-xs-12 col- md-offset-2 col-sm-offset-0 xs-offset-0">  
        <div class="form-box-inner"> 
         <h2 class="title text-center">Sign up now</h2> 
         <p class="intro text-center">It only takes 3 minutes!</p>    
         <div class="row"> 
          <div class="form-container col-md-5 col-sm-12 col-xs-12"> 
           <form class="signup-form"> 
            <%= form_for(resource, as: resource_name, url: user_registration_path(resource_name)) do |f| %>   <%= devise_error_messages! %>   
            <div class="form-group email"> 
             <!-- <label class="sr-only" for="signup-email">Your email</label> 
             <input id="signup-email" type="email" class="form-control login-email" placeholder="Your email"> --> 
             <%= f.label :email, class: 'sr-only' %> 
             <%= f.text_field :email, class: 'form-control login-email', placeholder: "Your email" %> 
            </div><!--//form-group--> 
            <div class="form-group password"> 
             <%= f.label :password, class: 'sr-only' %> 
             <%= f.text_field :password,  class: 'form-control login-password', placeholder: "Your password" %> 
            </div> 
            <!--//form-group--> 
            <div class="col-md-12 col-sm-12  col-xs-12 form-group"> 
            <%= f.submit "Sign up", class: 'btn btn-block btn-cta-primary' %> 
           </div> 
            <p class="note">By signing up, you agree to our terms of services and privacy policy.</p> 
            <p class="lead">Already have an account? <%= link_to "Log in", user_session_path, class: "login-link" %> 
            </p> 
            <% end %> 
           </form> 
          </div><!--//form-container--> 
          <div class="social-btns col-md-5 col-sm-12 col-xs-12 col-md-offset-1 col-sm-offset-0 col-sm-offset-0"> 
           <div class="divider"><span>Or</span></div>      
           <ul class="list-unstyled social-login"> 
            <li><button class="twitter-btn btn" type="button"><i class="fa fa-twitter"></i>Sign up with Twitter</button></li> 
            <li><button class="facebook-btn btn" type="button"><i class="fa fa-facebook"></i>Sign up with Facebook</button></li> 
            <li><button class="github-btn btn"  type="button"><i class="fa fa-github-alt"></i>Sign up with Github</button></li> 
            <li><button class="google-btn btn" type="button"><i class="fa fa-google-plus"></i>Sign up with Google</button></li> 
           </ul> 
           <p class="note">Don't worry, we won't  post anything without your permission.</p> 
          </div><!--//social-login--> 
         </div><!--//row--> 
        </div><!--//form-box-inner--> 
       </div><!--//form-box--> 
      </div><!--//row--> 
     </div><!--//container--> 
    </section><!--//signup-section--> 
</div><!--//upper-wrapper--> 
<!--FOOTER --> 

<!-- Javascript -->   
<script> 
    /* ======= Fixed header when scrolled ======= */  
$(window).on('scroll load', function() 
{ 

    if ($(window).scrollTop() > 0) 
    { 
     $('#header').removeClass('scrolled'); 
    } 
    else 
    { 
     $('#header').addClass('scrolled'); 

    } 
}); 
</script> 

DEViSE регистрации контроллера маршруты:

cancel_user_registration GET  /users/cancel(.:format)    devise/registrations#cancel 
    user_registration POST  /users(.:format)      devise/registrations#create 
new_user_registration GET  /users/sign_up(.:format)    devise/registrations#new 
edit_user_registration GET  /users/edit(.:format)     devise/registrations#edit 
         PATCH /users(.:format)      devise/registrations#update 
         PUT  /users(.:format)      devise/registrations#update 
         DELETE /users(.:format)      devise/registrations#destroy 

Попытка переопределить DEViSE регистрации контроллера:

class SignupController::RegistrationsController <  Devise::RegistrationsController 


def new 
    #@user = User.new 
    @resource_name = User.new 
end 

def create 
    @resource_name = User.new(user_params) 


    #if @user.save 
    if @resource_name.save 
    flash[:notice] = "Your user account has been created!" 
    create_session(@resource_name) 
    redirect_to '/' 

    else 
    flash[:error] = "Your user account was not created, please try again." 
    render :new 
end 
end 

def user_params 
params.require(:user, :email) 
end 
end 
+0

Извините, но в основном ничего правильно с тем, как вы bulldozering над завещанием. Можете ли вы включить в вопрос, почему вы переопределяете контроллер разработки и чего хотите достичь? – max

+0

В основном '@ resource_name' в разработке - это имя пользовательского класса, а не новый пользовательский экземпляр. '@ resource' - создаваемый ресурс. И вы действительно не должны переопределять весь контроллер, просто чтобы изменить представления или добавить дополнительный атрибут. Я бы начал с чтения документов и вики, как есть, как в принципе любой возможный сценарий. – max

+0

Я получил его из этого переполнения стека: http://stackoverflow.com/questions/13805695/bypassing-devise-gem-registration-form-to-create-a-new-user – SaintClaire33

ответ

1

В настоящее время существует одна форма внутри другого:

<form class="signup-form"> 
    <%= form_for... %> 

Однако, это невозможно развить формы. Внешняя форма отправляется и отправляется на текущий URL страницы.

Вы должны удалить внешнюю форму и добавить signup-form класс к form_for:

<%= form_for(resource, as: resource_name, url: user_registration_path(resource_name), html: {class: 'signup-form'}) do |f| %> 
+0

Спасибо @lest, который работал Я могу для успешного создания пользователя – SaintClaire33

Смежные вопросы