0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Fctory_bot アソシエーション:belongs_toの記述

Last updated at Posted at 2021-09-19

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 確認 ```
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?