Rails Active Record Instance Variables
-
22-08-2019 - |
Question
My questions is in regards to this AR and its instance variable @saved
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
It is my understanding that the instance variables will keep their values through 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 in regards to these instance variables? Thank you
Solution
you're using the instance variable @saved inside a class method, the @saved var then belongs to the class, not to its instances, so you cannot call it from an instance method like #saved?.
what you can do, is, at the top of the class add:
attr_accessor :saved
and inside the create_phone_number method, replace:
@saved = true
with:
@new_phone.saved = true
then it should work
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow