Samuel-Zacharie Faure
Samuel-Zacharie Faure

Reputation: 1152

Save date in database with rails

So, I'm new to rails so this is probably a newbie question, but I didn't find any help for this problem anywhere...

Let's say I have a database containing "stories" here. The only column are the title and a timestamp :

  create_table :stories
    add_column :stories, :title, :string
    add_column :stories, :date, :timestamp

I have a form in my views so I can create a new story by inputing a title :

<%= form_for @story do %>
  <input type="text" name="title" value="Story title" />
  <input type="submit" value="Start a story" />
<% end %>

I have this on my controller :

  def create
    Story.create title:params[:title]
    redirect_to "/stories"
  end

And the model 'Story' works fine. So, when I create a new story, everything looks fine. My goal however is to be able to sort the stories by date (hence the :date timestamp). How can I make it so the current date is stocked in the :date timestamp, so I can sort my items by date ?

Thank you very much in advance

Upvotes: 0

Views: 1014

Answers (3)

asalgan
asalgan

Reputation: 326

Without having to recreate the table from scratch, in terminal run 'rails g migration add_timestamps_to_stories' - find the newly created migration file, make sure it has the following:

def change
  add_timestamps :stories
end

Run rake db:migrate

This adds two new columns, created_at and updated_at, you'll be able to sort by created_at from that point. Be sure to update previous records that don't have a created_at date (since it'll be nil) so you don't run into errors.

Upvotes: 0

Omnigazer
Omnigazer

Reputation: 831

If you only want to track the creation timestamp of your story records, you could do it like this in your migration:

create_table do |t|
  t.string :title
  t.timestamps
end

In addition to your title field, this would create "created_at" and "updated_at" fields which are handled by ActiveRecord for you, like Andrew Kim suggested.

Upvotes: 1

Andrew Kim
Andrew Kim

Reputation: 3335

def create
  Story.create(title:params[:title], date: DateTime.now
  redirect_to "/stories"
end

Upvotes: 1

Related Questions