0

У меня есть 2 формы на моей странице настроек пользователя, одна для всех основных настроек и одна для профиля профиля. Каждый раз, когда я пытаюсь обновить фотографию пользователя, я получаю сообщение об ошибке «пароли не могут быть пустыми», даже если поля пароля имеют другую форму.Редактирование пользователя Форма профиля Не работает

Код формы:

<%= form_for @user, :html=> { :multipart => true} do |f| %> 
    <%= render 'shared/error_messages', :object => f.object %> 
<div class="field"> 
    <%= f.label :name %><br /> 
    <%= f.text_field :name %> 
</div> 
<div class="field"> 
    <%= f.label :email %><br /> 
    <%= f.text_field :email %> 
</div> 
<div class="field"> 
    <%= f.label :password %><br /> 
    <%= f.password_field :password %> 
</div> 
    <div class="field"> 
    <%= f.label :password_confirmation, "Confirmation" %><br /> 
    <%= f.password_field :password_confirmation %> 
    </div> 
    <div class="actions"> 
     <%= f.submit "Update" %> 
    </div> 
<% end %> 

    <%= form_for @user, :html=> { :multipart => true} do |f| %> 
<%= f.file_field :photo %> 
     <br /> 
    <%= f.submit "Update" %> 
    <% end %> 

и мой user.rb файл:

class User < ActiveRecord::Base 

    attr_accessor :password 

    attr_accessible :name, :email, :password, :password_confirmation, :photo 

    has_attached_file :photo, 
        :styles => { 
        :thumb=> "50x50#", 
        :small => "220x220>" }, 
        :storage => :s3, 
        :s3_credentials => "#{Rails.root}/config/s3.yml", 
        :path => "/:style/:id/:filename" 

has_many :microposts, :dependent => :destroy 
has_many :relationships, :foreign_key => "follower_id", 
          :dependent => :destroy 
has_many :following, :through => :relationships, :source => :followed 
has_many :reverse_relationships, :foreign_key => "followed_id", 
            :class_name => "Relationship", 
            :dependent => :destroy 
has_many :followers, :through => :reverse_relationships, :source => :follower 

    email_regex = /\A[\w+\-.][email protected][a-z\d\-.]+\.[a-z]+\z/i 

    validates :name, :presence => true, 
       :length => { :maximum => 50 } 
    validates :email, :presence => true, 
       :format  => { :with => email_regex }, 
       :uniqueness => { :case_sensitive => false } 

    validates :password, :presence  => true, 
             :confirmation => true, 
             :length  => { :within => 6..40 } 

             before_save :encrypt_password 

Любая помощь очень ценится!

ответ

2

Затем вам нужно проверить, если поле пароля будет пустым, а затем проигнорируйте валидацию, и если пользователь заполнит что-нибудь в нем, он должен быть проверен, и если он на новом запись, она должна быть проверена всегда.

Так что, я бы сказал, он должен идти, как это:

validates :password, :presence  => true, 
             :if => :validate_password?, 
             :confirmation => true, 
             :length  => { :within => 6..40 } 

def validate_password? 
    if new_record? 
    return true 
    else 
    if password.to_s.empty? 
     return false 
    else 
     return true 
    end 
    end 
end 

также обновит метод encrypt_password, просто добавьте этот исходный код

def encrypt_password 
    return if password.to_s.empty? 
    ... 
    ... existing code 
    ... 
end 
+0

получил его! благодаря! – BTHarris

1

Проблема заключается в проверке присутствия вашего атрибута виртуального пароля.

Добавление :on => create остановит проверку при запуске при обновлении пользователя.

Попробуйте

validates_length_of  :password, :length => { :within => 6..40 }, :allow_blank => true 
validates_confirmation_of :password 
validates_presence_of  :password, :on => :create 

хороших рельсов отданных здесь: http://railscasts.com/episodes/250-authentication-from-scratch

+0

Хорошая идея, но она не работает, сеансы не работают. – BTHarris

+0

Простите, что вы подразумеваете под сессиями? – BigFive

+0

, очевидно, пароль сессии проверяется каждый раз, когда пользователь меняет страницы .. – BTHarris

1

просто редактируя проверки пароля с должен работать:

validates :password, :presence  => true, 
             :on => :create, 
             :confirmation => true, 
             :length  => { :within => 6..40 } 
+0

не мог заставить его работать, когда я использую форму профиля редактирования, он стирает пароли, чтобы войти в систему с пустым полем пароля – BTHarris