gpt4 book ai didi

ruby-on-rails - 如何获取模型实例变量

转载 作者:数据小太阳 更新时间:2023-10-29 08:33:22 25 4
gpt4 key购买 nike

我有一个简单的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com