comment(コメント)がstaff(ユーザー)、ostomy(投稿)にbelongs_to
models/comment.rb
class Comment < ApplicationRecord
belongs_to :ostomy #投稿
belongs_to :staff #ユーザー
validates :comment, {presence: true}
end
models/staff.rb
#ユーザーモデル
class Staff < ApplicationRecord
has_many :comments
end
models/ostomy.rb
#投稿モデル
class Ostomy < ApplicationRecord
has_many :comments
associationを用いて記述
has_manyはassociationの記述不要
factorys/cooments.rb
FactoryBot.define do
#医療staffがかくストマ記録
factory :comment do
sequence(:comment) { |n| "comment#{n}" }
association :ostomy
association :staff
end
end
models/comment_spec.rb
require 'rails_helper'
RSpec.describe Comment, type: :model do
pending "add some examples to (or delete) #{__FILE__}"
before do
@ostomy = build(:ostomy) #関係するオブジェクトostomyを作成
@staff = build(:staff) #関係するオブジェクトstaffを作成
@comment = build(:comment, staff: @staff, ostomy: @ostomy) #入れこむ
end
has_manyは記述不要でわからず記述してしまいエラーになった
rspec ./spec/models/comment_spec.rb
確認