Ian Durkan
Ian Durkan

Reputation: 1232

How to get model instance variables

I have a simple Rails application I'm using to try and learn Rails.

It has a database table I create like this using ActiveRecord:

class CreateMovies < ActiveRecord::Migration
  def up
    create_table :movies do |t|
      t.string :title
      t.string :rating
      t.text :description
      t.datetime :release_date
      t.timestamps
    end
  end

  def down
    drop_table :movies
  end
end

Here is my corresponding model class:

class Movie < ActiveRecord::Base
  def self.all_ratings
    %w(G PG PG-13 NC-17 R)
  end

  def name_with_rating()
    return "#{@title} (#{@rating})"
  end
end

When I call name_with_rating on an instance of Movie, all it returns is " ()" for any Movie. What is the correct syntax or method to call to get at the fields of the Movie instance from within an instance method of Movie?

Please note that the database has been properly populated with movie rows, etc. I've done rake db:create, rake db:migrate etc.

Upvotes: 2

Views: 2226

Answers (2)

Luis D Urraca
Luis D Urraca

Reputation: 2084

class Movie < ActiveRecord::Base
  def name_with_rating
     "#{title} (#{rating})"
  end
end

then in the console Movie.first.name_with_rating should work.

Upvotes: 1

Blake Taylor
Blake Taylor

Reputation: 9341

Active record attributes aren't implemented as instance variables. Try

class Movie < ActiveRecord::Base
  def name_with_rating()
    return "#{title} (#{rating})"
  end
end

Upvotes: 3

Related Questions