Active Rails Instance Variables

My questions concern this AR and its @saved instance variable

class PhoneNumber < ActiveRecord::Base has_one :user validates_presence_of :number def self.create_phone_number( user, phone_hash ) @new_phone = PhoneNumber.new(phone_hash) @user = user PhoneNumber.transaction do @user.phone_numbers << @new_phone @new_phone.save! @user.save! end @saved = true return @new_phone rescue ActiveRecord::RecordInvalid => invalid @saved = false return @new_phone end def saved? @saved ||= false end end 

As far as I understand, instance variables will retain their values ​​due to the existence of the instance.

When using this AR in my controller, saved? always returns false.

 @phone_number = PhoneNumber.create_phone_number(@active_user, params[:phone_number]) puts "add_phone_number" if @phone_number.saved? => always false 

What am I missing regarding these instance variables? Thanks you

+6
ruby-on-rails activerecord instance-variables
source share
1 answer

you use the @saved instance variable inside the class method, then @saved var belongs to the class, not its instances, so you cannot call it from the instance method, for example #saved ?.

what you can do is at the top of the add class:

  attr_accessor :saved 

and inside the create_phone_number method, replace:

  @saved = true 

from:

  @new_phone.saved = true 

then it should work

+7
source share

All Articles