2015-01-31 4 views
3

레일 4.1 애플리케이션에서 사용자 인증을 위해 마법을 사용합니다. 모든 것이 잘 작동합니다. 그러나 사용자 모델 (마법에 의해 인증 된)의 특정 속성을 업데이트하려고하면 암호가 비어 있고 너무 짧다는 오류가 발생합니다. 여기 Rails 암호가없는 모델의 Sorcery 속성 업데이트

> user = User.last 
=> # I get the user 
> user.update(about_me: "I'm a user") 
=> false 
> user.update(about_me: "I'm a user", password: "secret") 
=> true 

가 여기 내 모델 코드
응용 프로그램/모델/user.rb

class User < ActiveRecord::Base 
    authenticates_with_sorcery! 
    validates :password, presence: true, length: { minimum: 6 } 
    ..... 
end 

내 컨트롤러 코드
응용 프로그램/컨트롤러/users_controller.rb

의 콘솔에서 미리보기입니다
class UsersController < ApplicationController 
    ..... 
    def edit 
    @user = User.find(params[:id]) 
    end 

    def update 
    @user = User.find(params[:id]) 
    if @user.update(user_params) 
     redirect_to @user 
     flash[:notice] = "Profile successfully updated" 
    else 
     render 'edit' 
    end 
    end 

    private 
     def user_params 
     params.require(:user).permit(:username, :name, :email, :password, :about_me) 
     end 

end 

그리고 내 업데이트 형태 나 양식에서 암호 필드를 제거하면
응용 프로그램/뷰/사용자/edit.html.erb

<%= form_for @user, method: :put do |f| %> 
    <% if @user.errors.any? %> 
    <div class="alert"> 
     <p><%= pluralize(@user.errors.count, 'error') %></p> 
     <ul> 
     <% @user.errors.full_messages.each do |msg| %> 
      <li><%= msg %></li> 
     <% end %> 
     </ul> 
    </div> 
    <% end %> 
    <%= f.text_field :username, placeholder: 'Username' %> 
    <%= f.text_field :name, placeholder: 'Name' %> 
    <%= f.email_field :email, placeholder: 'Email' %> 
    <%= f.text_area :about_me, placeholder: 'About me' %> 
    <%= f.password_field :password, placeholder: 'Password' %> 
    <%= f.submit 'Save Changes', class: 'button' %> 
<% end %> 

, 내가 암호에 대한 오류가 비어있는 그것의 길이에 대해 얻을. 이것은 마법과 관련이 있습니까? 아니면 레일 자체가없는 것입니까? 더 나은 방법으로 업데이트 할 수 있습니까? 다른 이메일에 영향을주지 않고 이메일 필드 만 알려주시겠습니까?

+0

** 업데이트 : ** ** 모델에서 allow_blank : true를 사용할 수 있음을 알았습니다. 이렇게하면 사용자가 비밀번호없이 등록 할 수 있으므로 사용자 컨트롤러의 만들기 작업에서 조건을 사용하는 것이 좋습니다. 내가 작동하게되면 대답을 게시 할 것입니다. 어쨌든, 나는 이것이 올바른 방법이라고 생각하지 않습니다. – prajwaldp

+0

allow_blank를 true로 표시하는 것은 올바른 방법이 아닙니다. 오히려 사용자 모델에서 조건부 유효성 검사를 수행 할 수 있습니다. 어떤 조건에서 유효성 검사와 마찬가지로 검사를 건너 뛰어야합니다. 마치 기존 사용자가 편집하려는 경우 조건이 지정된 유효성 검사를 전달하면 기존 사용자가됩니다. 내 아래 답변을 확인하십시오. 의심 스러울 것입니다. – Ajay

답변

4
class User < ActiveRecord::Base 
    authenticates_with_sorcery! 
    validates :password, presence: true, length: { minimum: 6 }, if: :new_user? 

    private 
    def new_user? 
    new_record? 
    end 
end 

검증은 우리가 우리 자신의 개인 검증 방법 NEW_USER을 추가하는 대한 new_record이의 경우에만 확인됩니다? 이 함수는 일반적인 가입/등록 중에 true를 반환합니다. 따라서 이러한 가입시 암호 유효성 검사 만 필요합니다.

편집하는 동안 사용자는 기존 사용자/new_record가됩니까? 거짓을 반환합니다. 따라서 암호 확인은 건너 뜁니다.

두번째 방법은 다음과 같습니다

class User < ActiveRecord::Base 
    attr_accessor :skip_password 
    validates :password, presence: true, length: { minimum: 6 }, unless: :skip_password 
end 

#users_controller.rb 
def update 
    @user = User.find(params[:id]) 
    @user.skip_password = true 
    if @user.update(user_params) 
    redirect_to @user 
    else 
    render 'edit' 
    end 
end 

우리는 우리 자신의 사용자 정의 attr_accessor의 skip_password을 추가했습니다. skip_password 값을 true로 설정하면 편집/업데이트 중에 암호 유효성 검사를 건너 뜁니다.

두 방법 모두 도움이 되길 바랍니다. :)

+0

두 가지 방법 모두 매력처럼 작동했습니다. 두 번째 방법은 콜론이 필요합니다 (: skip_password가 아니라면 : skip_password 제외). 논리가 모델 내에 있기 때문에 첫 번째 방법을 사용하는 것을 선호했습니다. 사용자가 자신의 속성을 업데이트 한 후에 빈 문자열로 업데이트되는 암호에 대한 의문이 있었지만 그렇지 않은 것으로 밝혀졌습니다. 감사! – prajwaldp

+0

예 논리가 모델에만 축적되므로 첫 번째 것이 더 바람직합니다. 오타를 지적 해 주셔서 감사합니다 (: : skip_password 제외).그 중 하나를 업데이트했습니다. – Ajay