a45b
a45b

Reputation: 519

Can I modify the timestamps column name in Rails 4.2 from created_at to like created

I want to change the timestamps default column names from created_at to createdDatetime and updated_at to updatedDatetime.

Is there any way to do so? When I migrate it, can I create these names as I wish?

Upvotes: 3

Views: 2536

Answers (2)

gayavat
gayavat

Reputation: 19408

it is possible to set field names manually:

http://api.rubyonrails.org/classes/ActiveRecord/Timestamp.html#method-i-timestamp_attributes_for_create

def timestamp_attributes_for_create
    [:createdDatetime]
end

my answer is duplicate https://stackoverflow.com/a/13457972/1007043 Also, there are info about Rails 5 solution

Upvotes: 1

Michael Gaskill
Michael Gaskill

Reputation: 8042

The quickest, most flexible solution that doesn't involve monkey-patching is this:

class Product < ActiveRecord::Base
  before_create :set_time_stamps
  before_save :set_time_stamps

private
  def set_time_stamps
    self.createdDatetime = DateTime.now if self.new_record?
    self.updatedDatetime = DateTime.now
  end
end

You are in complete control in each model class (database table) of which column names are updated. You can control the format if you choose, in case the field is a timestamp, milli-time, or even a formatted string (it happens!). This solution is highly likely to survive major version upgrades of Rails, since this is a part of the public interface for ActiveRecord.

If you have a number of models that behave identically, you can either make a base class or module to handle it.

The base class approach:

class TimeStamper < ActiveRecord::Base
  # TimeStamper is not intended for single-table inheritance
  self.abstract_class = true

  before_create :set_time_stamps
  before_save :set_time_stamps

private
  def set_time_stamps
    self.createdDatetime = DateTime.now if self.new_record?
    self.updatedDatetime = DateTime.now
  end
end

And then derive your models from this, like so:

class Product < TimeStamper
  # inherits all of the ActiveRecord::Base and TimeStamper functionality
end

In your migration, you'd simply need to include the fields like you would any others:

class CreateProducts < ActiveRecord::Migration
  def change
    create_table :products do |t|
      # Product fields

      t.datetime :createdDatetime, null: false
      t.datetime :updatedDatetime, null: false
    end
  end
end

You will have to add those manually, but it's not an onerous task if that's what you need to do. Rails gives you the flexibility to deviate from convention when your requirements dictate, and in this case the deviation is both benign and simple to handle manually.

Upvotes: 3

Related Questions