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
A variable set in Rails controller starting with @ sign are called instance variables. The specialty of instance variables is that they're available in our Rails views. We don't need to pass them explicitly to our Rails views. That's why in the index.
class . There are no "static methods" in the C# sense in Ruby because every method is defined on (or inherited into) some instance and invoked on some instance. Accordingly, they can access whatever instance variables happen to be available on the callee.
Rails Active Records provide an interface and binding between the tables in a relational database and the Ruby program code that manipulates database records. Ruby method names are automatically generated from the field names of database tables.
The value of an instance variable can be changed by any method in the class, but it is not accessible from outside the class. Instance variables are usually initialised when the object is created. This is done with an instance initializer block, a special block of code run when an object is created.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With