Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Active Record Instance Variables

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

like image 624
stellard Avatar asked Mar 31 '09 19:03

stellard


People also ask

What is an instance variable in Rails?

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.

Can a class method access instance variables Ruby?

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.

What is Active Records in Rails?

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.

Can instance variables be accessed outside the class?

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.


1 Answers

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

like image 133
Maximiliano Guzman Avatar answered Oct 18 '22 10:10

Maximiliano Guzman