-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

Why it works but

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

does not work??

engineersmnky
  • 25,495
  • 2
  • 36
  • 52
user1013369
  • 239
  • 1
  • 4
  • 9
  • Related: http://stackoverflow.com/questions/14603633/anti-private-property-of-setter-method – sawa Nov 07 '13 at 17:26
  • not sure what issue you are having but you could change to this for such a simple method `before_validation {|user| user.login = user.email unless user.email.blank?}` – engineersmnky Nov 07 '13 at 17:27
  • Duplicate of: http://stackoverflow.com/questions/13715254/ruby-calling-setters-from-within-an-object – sawa Nov 07 '13 at 17:30
  • Duplicate of: http://stackoverflow.com/questions/4699687/when-to-use-self-foo-instead-of-foo-in-ruby-methods – sawa Nov 07 '13 at 17:31
  • Duplicate of: http://stackoverflow.com/questions/15297161/ruby-self-keyword – sawa Nov 07 '13 at 17:31

2 Answers2

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.

Kyle d'Oliveira
  • 6,382
  • 1
  • 27
  • 33
-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

uno_ordinary
  • 458
  • 3
  • 9