N4. model relation

2020. 7. 5. 16:40Rails 5 on aws c9

 

두 모델의 관계에 대해 배워보자.

유저가 여러개의 포스트를 쓸 수 있다면

1:N의 관계이다

User has many posts / Post belongs to user

이때 유저가 부모, 외래키를 가진쪽을 자식이라고 얘기한다.

외래키는 부모의 id등이 되어서, 자식의 부모가 누구인지 알아볼 때 쓴다.

가령 아래와같은 상황이라고 한다면,

Post의 user_id를 보면, 누가 쓴 글인지 알 수 있다.

이때 규칙은 (부모명)_(부모의속성) 이다.

ubuntu:~/environment/noar (master) $ rails g model Post

Running via Spring preloader in process 7687
      invoke  active_record
      create    db/migrate/20200617003652_create_posts.rb
      create    app/models/post.rb
      invoke    test_unit
      create      test/models/post_test.rb
      create      test/fixtures/posts.yml
class CreatePosts < ActiveRecord::Migration[5.0]
  def change
    create_table :posts do |t|
      t.text :content
      t.belongs_to :user

      t.timestamps
    end
  end
  #user_id를 색인해서 빠르게 찾아올 수 있게 한다.
  #add_index :posts, :user_id
  #이는 t.intager :user_id 를 t.belongs_to :user 로 바꿔서 대체할수 있다. 
end
ubuntu:~/environment/noar (master) $ rake db:migrate
== 20200617003652 CreatePosts: migrating ======================================
-- create_table(:posts)
   -> 0.0058s
== 20200617003652 CreatePosts: migrated (0.0068s) =============================

특정 유저가 작성한 모든 포스트 불러오기

Post.where(user_id: 2)

Post.where(user_id: User.last.id)

user.posts 를 해서 볼 수 있으면 좋을것 같다.(가령 current_user.posts)

이렇게 한번에 뽑아올 수 있는 명령어를 만들것이다.

models/user.rb

class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable

  has_many :posts
end

해당 포스트를 쓴 글쓴이의 객체 불러오기

model/post.rb

class Post < ApplicationRecord
    belongs_to :user
end

유저가 쓴 글이 몇개인지 확인해보는법

user.posts.size

⇒ 2

user.posts.count

⇒ 쿼리가 날라간 후

⇒ 2

'Rails 5 on aws c9' 카테고리의 다른 글

N5-1. post 결과물을 json으로 응답받기  (0) 2020.07.05
N5. Post 리스트와 생성  (0) 2020.07.05
N3. Devise 적용하기  (0) 2020.07.05
N2. Materialize 적용하기  (0) 2020.07.05
N1. NoAR 만들기 - post 컨트롤러 생성  (0) 2020.07.05