Search code examples
ruby-on-railsrubymodels

Rails - Why not use @ symbol in model class?


New to rails. I'm having trouble understanding why I use score > 50 and not @score > 50 i nthe following example? Doesn't the @ sign imply an instance variable, which is what I should use in classes?

Where is the class getting the score variable from? I was under the impression that it would be considered local if it's not prefixed with an @ ?

class HighScore < ActiveRecord::Base

  attr_accessible :game, :score
  validate :verify_inputs

  def verify_inputs

    # Why is this line not @score > 50??
    if score > 50
      errors.add( :score, 'Custom error message. Score cannot be more than 50' )
    end
  end
end

Solution

  • Where is the class getting the score variable from?

    First of all, since there's no local variable score, then it's a method score. There must be a column score in corresponding DB table. ActiveRecord reads the schema and creates getter and setter methods for every column (dynamically, at runtime). Try this:

    HighScore.new.methods
    

    You should see there two methods, score and score=.

    Doesn't the @ sign imply an instance variable

    Yes, it does signify a local variable

    which is what I should use in classes

    Not necessarily. Most of the times, you should use accessor methods. That's what they are for.