我有一个简单的 Rails 应用程序,用于尝试和学习 Rails。
它有一个我使用 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
这是我对应的模型类:
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
当我在 Movie 实例上调用 name_with_ rating 时,对于任何 Movie,它返回的只是“()”。从 Movie 的实例方法中调用获取 Movie 实例的字段的正确语法或方法是什么?
请注意,数据库已正确填充电影行等。我已经完成了 rake db:create、rake db:migrate 等。
最佳答案
事件记录属性不作为实例变量实现。尝试一下
class Movie < ActiveRecord::Base
def name_with_rating()
return "#{title} (#{rating})"
end
end
关于ruby-on-rails - 如何获取模型实例变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12065882/