Search code examples
ruby-on-railsrubydatabaseseeding

Rails seed database


I am trying to add a reviews table to my database, and seed some dummy data into the tables.

I can insert into the reviews table through psql command line but when seeding I get errors. Im not sure what I am missing, any help would be greatly appreciated. Thanks!

This is my migration I ran

 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

This is the error I get when running 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

This is my seed file

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

puts "Finding or Creating REVIEWS ..."

Review.destroy_all

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

My schema, seems to be fine and has both

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

as well as having both

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

Here is my review model

class Review < ActiveRecord::Base

 belongs_to :product

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

end

Solution

  • You're missing belongs_to :user to your review model.