-1
class User < ActiveRecord::Base
  before_validation :ensure_login_has_a_value

  validates :login, :email, presence: true

  protected
    def ensure_login_has_a_value
      if login.nil?
        self.login = email unless email.blank?
      end
    end
end

为什么它有效但是

protected
  def ensure_login_has_a_value
    if login.nil?
      #self.login = email unless email.blank?
      # the change  
      login = email unless email.blank?
    end
  end

不工作??

4

2 回答 2

1

In the second one,

  login = email unless email.blank?

Is creating a local variable call login and assigning it email

The first one actually assigns it to the attribute of the model.

于 2013-11-07T17:26:33.863 回答
-1

When you are using login - it uses the getter, provided by ActveRecord, and if you would like to use login= you should declare login as attr_accessible

于 2013-11-07T17:26:49.270 回答