开发者

Turn off "updated_at" column in Rails

开发者 https://www.devze.com 2023-01-08 20:21 出处:网络
I have a simple \"Log\" model, that records the fact of calling controller\'s action. Entries of this \"log\" record are supposed to be created once and never altered. Also, I will have many of these

I have a simple "Log" model, that records the fact of calling controller's action.

Entries of this "log" record are supposed to be created once and never altered. Also, I will have many of these records i开发者_Go百科n the database.

So, there is no need for "updated_at" column (don't need to waste the memory on HDD).

How can I tell to Rails to leave only "created_at" column and not to use "updated_at"?

Is there any way to make the "Log" model read only?


I presume you have the updated_at column because you used the t.timestamps shorthand in your model's migration file. If you don't want the column then you can specify what you do want explicitly:

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


You can make the model readonly by adding a readonly? method to the model.

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

The example above was adopted from here.

If you don't need the updated_at column, just remove (or don't add it) it from your database. Rails won't update what's not there.

0

精彩评论

暂无评论...
验证码 换一张
取 消