1
は、私は、ユーザーテーブルとコメントの関連付けを作成しようとしていますが、私は、レールコンソールにアクセスし、それが動作するかどうかを確認しようとしないとき、それは私に次のエラーを与える:Ruby On Rails;未定義のメソッド `コメント
user = User.first
user.comments
undefined method `comments'
以下は私が使用しているコードです。
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
最新のバージョンのrubyを使用しています。
ありがとうございました!私は未定義のメソッドエラーのために何らかの理由が表示されない
このコマンドを実行 保留しているかもしれあなたはuserテーブルのすべてのレコードを持っていますか? 'User.first'は何を返しますか? – moveson
こんにちは@MrYoshiji @moveson User.first <ユーザID:1、ユーザ名: "john"、メール: "carma"、created_at: "2017-11-02 18:49:02"、updated_at: "2017- 11月2日18時49分02" 秒> User.first.comments NoMethodError:私は重要な場合には、ルビーマインを使用してい0x4535058> :未定義のメソッドが '#<ユーザーのコメント。 – Blinhawk
ユーザーとコメントの間にこの関係を作成した後でコンソールをリロードしましたか? (IRBに 'reload!'をタイプするか、 'exit'をもう一度' rails c'を入力してください) – MrYoshiji