views:

49

answers:

3

Just started learning Rails (3). I am tearing my hair out trying to find how to do something presumably utterly trivial: access the value of a model instance's field, from inside a method on that model.

In my case:

def formal_name
  @title + " " + @forename + " " + @surname
end

All three @properties (which are all fields on the table in the database) return nil. They shouldn't.

Incredibly, how to access fields isn't discussed at http://guides.rails.info/, and google turns up nothing.

BTW, I'm coming from Django where this stuff is obvious.

A: 

You have to omit the @, you access them via getter methods. In some cases you must use self.<field> due to ambiguity.

igorw
+4  A: 

The @ syntax is used for instance variables that (for example) get populated in controllers and then used in views. Not what you're doing here.

You actually just need

def formal_name
  title + " " + forename + " " + surname
end
JacobM
A: 
class MyModel << ActiveRecord

  def formal_name
    title = self.title # return title attribute of instance
    forename = self.forename
    surename = self.surname

    # or something like this
    self.title + self.surename
  end

end
Meduza