问题描述:

I am currently having a problem with RoR. I need the fields created_at and updated_at in in my tables for further use. However rails doesn't seem to add them even though I ask rails to. These are my models:

Picture.rb

class Picture < ActiveRecord::Base

belongs_to :category

has_many :comments, dependent: :destroy

mount_uploader :photo, PhotoUploader

validates_presence_of :photo

end

Category.rb

class Category < ActiveRecord::Base

has_many :pictures, dependent: :destroy

validates :name, presence: true, uniqueness: { case_sensitive: false }

end

Comment.rb

class Comment < ActiveRecord::Base

belongs_to :user

belongs_to :picture

validates :text, presence: true

end

These are my migrations:

class CreateCategories < ActiveRecord::Migration

def change

create_table :categories do |t|

t.string :name

t.timestamps

end

end

end

class CreatePictures < ActiveRecord::Migration

def change

create_table :pictures do |t|

t.string :description

t.references :category, index: true

t.timestamps

end

add_foreign_key :pictures, :categories

end

end

class AddPhotoToPictures < ActiveRecord::Migration

def change

add_column :pictures, :photo, :string

end

end

class CreateComments < ActiveRecord::Migration

def change

create_table :comments do |t|

t.string :text

t.references :user, index: true

t.references :picture, index: true

t.timestamps

end

add_foreign_key :comments, :users

add_foreign_key :comments, :pictures

end

end

class AddTimeStampsToPicture < ActiveRecord::Migration

def change_table

change_table :pictures do |t|

t.timestamps

end

end

As you can see I am trying to add the 2 columns. When I try seeing the created_at field it will say "undefined method created_at'" . I am checking in rails c to see if the fields are there but no, the fields do not exist. I am using PG gem . Also I am using carrierwave gem to upload the pictures. Why would rails not include these 2 columns ? Here is a link to the project itself.

As coorasse suggested I took a look at the schema.

create_table "pictures", force: :cascade do |t|

t.string "description"

t.integer "category_id"

t.string "photo_file_name"

t.string "photo_content_type"

t.integer "photo_file_size"

t.datetime "photo_updated_at"

t.string "photo"

end

It seems it didn't update herself. Why?

网友答案:

To force shema to be updated you would drop the db and recreate it.

But be aware - it will erase whole database.

rake db:drop && rake db:create && rake db:migrate

You can't just edit the schema or migration files. If you are adding new columns - you should do it through new migration.

But if you are taking the editing migrations files road you'll have (problems) to drop the DB and recreate it.

网友答案:

Check if you ran the migrations with rake db:migrate then double check your schema.rb file.

You have to run the migrations for your changes to take effect

相关阅读:
Top