I'm trying to create a comment association with the user table, but when I go to the rails console and do try to see if it works, it gives me the following error:
user = User.first
user.comments
undefined method `comments'
Below is the code that i'm using.
class CreateComments < ActiveRecord::Migration[5.1]
def change
create_table :comments do |t|
t.text :description
t.references :user, index: true, foreign_key: true
t.timestamps
end
end
end
class CreateUsers < ActiveRecord::Migration[5.1]
def change
create_table :users do |t|
t.string :username
t.string :email
t.timestamps
end
end
end
class Comment < ApplicationRecord
belongs_to :user
end
class User < ApplicationRecord
has_many :comments
end
Im using the latest version of ruby.
Thank you!
I don't see any reason for undefined method error, may be you have pending migrations run this command
rails db:migrate
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.