2

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.

2 Answers 2

3

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

class Movie < ActiveRecord::Base
  def name_with_rating()
    return "#{title} (#{rating})"
  end
end
Sign up to request clarification or add additional context in comments.

Comments

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.