2011-01-02 3 views
1

Ruby on Rails 응용 프로그램 (2.3.x)에서 작업 중이며 사용자가 로그인하거나 등록 할 수있는 양식을 만들고 싶습니다. 나는 이것을 같은 형식으로하고 싶다.로그인 또는 등록 (Ruby on rails)

로그인 양식 :

<% form_for @user do |f| %> 
<div id="form"> 
    <%= f.label :email, "E-mail" %> 
    <%= f.text_field :email %> 

    <%= f.label :password, "Password" %> 
    <%= f.password_field :password %> 

    <%= link_to "I don't have an account, "#", :id => "changeForm"%> 
    <%= f.submit "Login" %> 
</div> 
<% end %> 

ID입니다 "changeForm는"형식 요소를 변경하는 JS 기능을 트리거이 같은 양식 요소를 대체하는 JS 기능을 가지고있다. 당신이 URL을 누르면 그래서 HTML은 다음과 같습니다

<% form_for @user do |f| %> 
<div id="form"> 
    <%= f.label :name, "Name" %> 
    <%= f.text_field :name %> 

    <%= f.label :email, "E-mail" %> 
    <%= f.text_field :email %> 

    <%= f.label :password, "Password" %> 
    <%= f.password_field :password %> 

    <%= f.label :password_confirmation, "Password confirmation" %> 
    <%= f.password_field :password_confirmation %> 

    <%= link_to "I do have an account, "#", :id => "changeForm"%> 
    <%= f.submit "Register" %> 
</div> 
<% end %> 

내가 내 사용자 모델에 neccesary 검증을 추가 :

class User < ActiveRecord::Base 
    attr_reader :password 
    validates_presence_of :name, :email, :password 
    validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i 
    validates_confirmation_of :password 

하지만 당신은 당신이 얻을 이메일/비밀번호를 입력 할 때 어떤 일이 발생 이름이 누락되어 있고 암호 필드가 확인되지 않은 오류. 그래서 내가 이렇게 내 사용자 모델에 성가신 프로그래밍을 할 수 : 검증없이이 (이럴 더러운 코드를 컨트롤러에 있으면 안)

#if password_conf or the name are present the user has tried to register... 
if params[:user][:password_confirmation].present? || params[:user][:name].present? 
    #so we'll try to save the user 
    if @user.save 
    #if the user is saved authenticate the user 
    current_session.user = User.authenticate(params[:user]) 
    #if the user is logged in? 
    if current_session.user.present? 
     flash[:notice] = "succesvully logged 
     redirect_to some_routes_path 
    else 
     #not logged in... 
     flash[:notice] = "Not logged in" 
     render :action => "new"    
    end 
    else 
    #user not saved 
    render :action => "new" 
    end 
else 
    #So if the params[:user][:password_confirmation] or [:user][:name] weren't present we geuss the user wants to login... 
    current_session.user = User.authenticate(params[:user]) 
    #are we logged_in? 
    if current_session.user.present? 
     flash[:notice] = "Succesvully logged in" 
     redirect_to some_routes_path 
    else 
     #errors toevoegen  
     @user.errors.add(:email, "The combination of email/password isn't valid") 
     @user.errors.add(:password," ") 
     render :action => "new" 
    end 
end 
end 

작동합니다. 하지만 validates_presence_of 메소드를 사용하고 싶습니다. 얼굴에서 "컨벤션 오버 컨피그레이션"을 치고 싶지는 않습니다.

그래서 내가 양식에 숨겨진 필드를 추가 시도 또 다른 한가지 : 다음

#login form 
    <%= f.hidden_field :login, :value => true %> 
    # and ofcourse set it to false if we want to register. 

그리고 나는 방법 사용하고 싶었 : before_validation

before_validation_on_create do |user| 
    if params[:user].login == true #throws an error i know... 
     validates_presence_of :email, :password 
     validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i 
    else 
    validates_presence_of :name, :email, :password 
    validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i 
    validates_confirmation_of :password   
    end 
end 

을하지만이 때문에 작동하지 않습니다 나는 params에 접근 할 수 없다. 그리고 login은 사용자 객체의 속성이 아닙니다. 그러나 나는이 방법으로 사용자가 로그인하기를 원하면 이메일과 암호 매개 변수를 검증 할 수 있다고 생각했습니다. 사용자가 등록하려면 다른 모든 attrs.

내가 생각할 수있는 모든 것은 그것이 작동하기를 원하는 방식으로 작동하지 않습니다. 따라서 내 주요 목표는 다음과 같습니다.

사용자 모델의 유효성 검사 방법을 사용하여 로그인/등록을위한 양식. 그래서 우리가 로그인하기를 원하지만 어떠한 정보도 입력하지 않으면 => 검증 에러를줍니다. 사용자가 로그인하려고하지만 이메일/비밀번호 조합이 일치하지 않으면 "@ user.errors.add (: email,"조합은 db ... ")"로 표시됩니다. 그리고 사용자 등록에 대해서도 마찬가지입니다 ...

미리 감사드립니다!

당신은 적절한 컨트롤러 액션에 각 양식을 가리켜 야합니다
+0

왜 같은 경로로이 작업을 수행 하시겠습니까? – stef

+1

나는 Stef와 동의한다. 동일한 페이지에 사용자 로그인 또는 등록을 할 수 있지만 양식을 다른 컨트롤러 또는 작업에 제출해야합니다. –

답변

1

:

# Registration form 
<% form_for @user, :url => users_path do |f| %> 
... 
<% end %> 

# Login form, non-RESTful action 
<% form_for @user, :url => login_users_path do |f| %> 
... 
<% end %> 

이것은 당신이 당신의 UsersControllerlogin 행동이 가정,하지만 당신은 전용 컨트롤러를 갖고 싶은 경우 세션을 관리 :

# Use SessionsController (Sessions#Create) to create a new user session 
<% form_for @user, :url => sessions_path do |f| %> 
... 
<% end %> 
+1

좋은 답변이지만, 장래에'sessions/path'와 같은 더 간단한 라우팅 도우미를 사용하도록 유도하십시오.이 라우팅 도우미는'config/routes.rb'에서 스스로 생성해야합니다. –

+0

좋습니다. 내 대답이 업데이트되었습니다. –

+0

감사합니다. 남자 남자 나는 정말로 바보 같은 느낌이 들지만 ... 8 시간 코딩을하면 오류가 생기기 시작합니다 ... –