Rails种子数据库

时间:2017-05-13 16:45:06

标签: ruby-on-rails ruby database seeding

我正在尝试将评论表添加到我的数据库中,并将一些虚拟数据添加到表中。

我可以通过psql命令行插入评论表,但是在播种时我会收到错误。我不确定我错过了什么,任何帮助将不胜感激。谢谢!

这是我的迁移

 class CreateReviews < ActiveRecord::Migration
   def change
    create_table :reviews do |t|
     t.references :user, index: true, foreign_key: true
     t.references :product, index: true, foreign_key: true
     t.text :description
     t.integer :rating

     t.timestamps null: false
    end
   end
 end

这是我在运行db:reset

时遇到的错误
[DEPRECATION] requiring "RMagick" is deprecated. Use "rmagick" instead
Finding or Creating REVIEWS ...
rake aborted!
NoMethodError: undefined method `user' for #<Review:0x00000006feb4a0>
Did you mean?  user_id

这是我的种子文件

user1 = User.find_or_create_by! ({first_name: 'bob', last_name:'long', email: 'bob@email.com', password_digest: '1234'})

puts "Finding or Creating REVIEWS ..."

Review.destroy_all

user1.reviews.create!({
 product_id: 1,
 description: 'some text',
 rating: 3
})

我的架构似乎很好并且都有

add_index "reviews",["product_id"],name:"index_reviews_on_product_id",using: :btree   add_index "reviews",["user_id"],name:"index_reviews_on_user_id",using: :btree

以及两者兼有

add_foreign_key "reviews", "products"   add_foreign_key "reviews", "users"

这是我的评论模型

class Review < ActiveRecord::Base

 belongs_to :product

 validates :product, presence: true
 validates :user, presence: true
 validates :rating, presence: true

end

1 个答案:

答案 0 :(得分:1)

您的审核模型遗漏了belongs_to :user