未定义的方法 after_save rails 4.1.1 和 ruby 2.1.5
undefined method after_save rails 4.1.1 and ruby 2.1.5
所以我的电脑刷新了(所有应用程序都丢失了)所以我不得不重新安装 rails 然后我回到刷新之前我正在做的项目。当我重新启动项目文件夹并尝试迁移数据库时,出现此错误:
C:\RailsProjects\Blog>rake db:migrate
DL已弃用,请使用Fiddle
-- after_save(:assign_date)
-- after_save(:assign_date)
耙子中止!
NoMethodError: 未定义的方法after_save' for #<ActiveRecord::Migration:0x262be10>
C:/RailsProjects/Blog/db/migrate/20150318235356_add_date_to_articles.rb:7:in
'
C:/RailsProjects/Blog/db/migrate/20150318235356_add_date_to_articles.rb:1:在`'
而我的迁移文件如下:
class AddDateToArticles < ActiveRecord::Migration
def change
add_column :articles, :date, :date
end
after_save :assign_date
protected
def assign_date
self.date = Date.current
end
end
关于我可以更改的内容有什么建议吗?我觉得这可能是我的 rails 安装,但我已经更新了 rails gem 但它仍然失败。
其实你做错了。回调永远不会写入迁移文件。如果您想为所有现有文章分配日期,则:
class AddDateToArticles < ActiveRecord::Migration
def change
add_column :articles, :date, :date
Article.all.each do |article|
article.date = Date.current
article.save
end
end
end
希望对您有所帮助。
您必须在模型中而不是在迁移中定义 after_save
回调。您可能有一个 Article 模型,您将在其中定义
class Article < ActiveRecord::Base
after_save :assign_date
protected
def assign_date
self.date = Date.current
end
end
但要小心,因为我认为这不会达到您的预期。如果你真的想在每次创建对象时保存它,你必须在 before_save
回调中 运行 它。
而且我还要告诉你,你真的不需要它!在您的 table 中创建一个字段 created_at
或 created_on
,而不是 date
(非常糟糕的名称),Rails 将完全为您完成,无需任何类型的回调。
created_at
将保存对象创建时间的时间戳,created_on
将保留日期而不是时间戳。
您还有另一个字段 updated_at/on
,它将保留上次更新的 timestamp/date。
所以我的电脑刷新了(所有应用程序都丢失了)所以我不得不重新安装 rails 然后我回到刷新之前我正在做的项目。当我重新启动项目文件夹并尝试迁移数据库时,出现此错误:
C:\RailsProjects\Blog>rake db:migrate
DL已弃用,请使用Fiddle
-- after_save(:assign_date)
-- after_save(:assign_date)
耙子中止!
NoMethodError: 未定义的方法after_save' for #<ActiveRecord::Migration:0x262be10>
C:/RailsProjects/Blog/db/migrate/20150318235356_add_date_to_articles.rb:7:in
'
C:/RailsProjects/Blog/db/migrate/20150318235356_add_date_to_articles.rb:1:在`'
而我的迁移文件如下:
class AddDateToArticles < ActiveRecord::Migration
def change
add_column :articles, :date, :date
end
after_save :assign_date
protected
def assign_date
self.date = Date.current
end
end
关于我可以更改的内容有什么建议吗?我觉得这可能是我的 rails 安装,但我已经更新了 rails gem 但它仍然失败。
其实你做错了。回调永远不会写入迁移文件。如果您想为所有现有文章分配日期,则:
class AddDateToArticles < ActiveRecord::Migration
def change
add_column :articles, :date, :date
Article.all.each do |article|
article.date = Date.current
article.save
end
end
end
希望对您有所帮助。
您必须在模型中而不是在迁移中定义 after_save
回调。您可能有一个 Article 模型,您将在其中定义
class Article < ActiveRecord::Base
after_save :assign_date
protected
def assign_date
self.date = Date.current
end
end
但要小心,因为我认为这不会达到您的预期。如果你真的想在每次创建对象时保存它,你必须在 before_save
回调中 运行 它。
而且我还要告诉你,你真的不需要它!在您的 table 中创建一个字段 created_at
或 created_on
,而不是 date
(非常糟糕的名称),Rails 将完全为您完成,无需任何类型的回调。
created_at
将保存对象创建时间的时间戳,created_on
将保留日期而不是时间戳。
您还有另一个字段 updated_at/on
,它将保留上次更新的 timestamp/date。