0
1

More than 3 years have passed since last update.

rails リレーション色々

Last updated at Posted at 2020-05-16
  • 1対多

ツイート機能

class User
  has_many :twees
end

class Twitter
  belongs_to user
end

## schema
users
 name:string

tweets
 body:string
 user:refrences
  • 自己参照型

like機能


class User < ApplicationRecord
  has_many :likers,foreign_key: "liker_id",class_name: "Like"
  has_many :likeds,foreign_key: "liked_id",class_name: "Like"
end

class Like < ApplicationRecord
  belongs_to :user, foreign_key: "liker_id", class_name: "User"
  belongs_to :user, foreign_key: "liked_id" , class_name: "User"
end

## schema
users
 name:string

likes
  liker_id:integer
  liked_id:integer
  • 多対多 && accepted_nested_for

投稿記事とカテゴリー

class Post
  has_many :post_categoris
  has_many :categories, through: :post_categoris
  accepts_nested_attributes_for :post_categoris, allow_destroy: true, reject_if: :all_blank
end

class Category
  has_many :post_categoris
  has_many :posts, through: :post_categoris
end

class PostCategory
  belongs_to :post 
  belongs_to :category
end

## schema
posts
- body
categoris
- name

post_categories
- post_id
- category_id

## 実装イメージ
どちらからも画面を作るときに、多対多になるのかも
=> カテゴリー主体の機能がなければ 1 - *でいいのではないか

投稿一覧機能

投稿1 カテゴリー1 カテゴリー2
投稿2 カテゴリー3 カテゴリー4

カテゴリー一覧機能

カテゴリー1 投稿数
カテゴリー2 投稿数
  • ポリモーフィック(中々体に染み込まない)

Userが複数のタグをもつ
Postが複数のタグを持つ

## 図
User 1 - * Taguser.tags user.tags.first.tagable == user
Post 1 - * Tagpost.tags post.tags.first.tagable == post


class User
  has_many :tags ,as: :tagable
end

class Post
  has_many :tags ,as: :tagable
end


class Tag
  belongs_to :tagable, polymorphic: true
end


## schema

  "posts"
    t.string "name"
    t.string "desc"

  "tags"
    t.string "name"
    t.string "tagable_type"
    t.integer "tagable_id"

  "users"
    t.string "name"
    t.integer "age"
0
1
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
1