关闭Rails中的“updated_at”列
我有一个简单的“Log”模型,它记录调用控制器动作的事实。
这个“日志”记录的条目应该被创建一次并且从不改变。 此外,我将在数据库中有许多这些记录。
因此,不需要“updated_at”列(不需要浪费硬盘上的内存)。
如何告诉Rails只留下“created_at”列而不使用“updated_at”?
有没有办法让“Log”模型只读?
您可以通过添加readonly?
来使模型readonly?
模型的方法。
class Log < ActiveRecord::Base # Prevent modification of existing records def readonly? !new_record? end # Prevent objects from being destroyed def before_destroy raise ActiveRecord::ReadOnlyRecord end end
上面的例子是从这里采用的。
如果您不需要updated_at
列,只需从数据库中删除(或不添加)它。 Rails不会更新不存在的内容。
我假设您有updated_at
列,因为您在模型的迁移文件中使用了t.timestamps
简写。 如果您不想要该列,那么您可以明确指定您想要的内容:
class Log < ActiveRecord::Migration def self.up create_table :logs do |t| t.column :foo, :string t.column :created_at, :datetime end end def self.down drop_table :logs end end