SlideShare ist ein Scribd-Unternehmen logo
1 von 25
Downloaden Sie, um offline zu lesen
Railsモデル設計ケーススタディ
ActiveRecordのアソシエーション
has_one
has_many
belongs_to
has_many :through
has_and_belongs_to_many
ポリモーフィック
STI
自己結合
多対多ケース
記事とタグ
ユーザと興味のあるカテゴリ
どっちつかうの問題1
has_many :through
vs
has_and_belongs_to_many
基本、has_many :through
has_and_belongs_to_manyは、中間テーブルが隠蔽され
ていて一見良さそうに見えるけど、把握しにくい。
has_many :through実装例
./bin/rails g model Product name
./bin/rails g model Order total_price:integer
./bin/rails g model ProductOrder product:references order:references
mysql> desc product_orders;
+------------+----------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+----------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| product_id | int(11) | YES | MUL | NULL | |
| order_id | int(11) | YES | MUL | NULL | |
| created_at | datetime | NO | | NULL | |
| updated_at | datetime | NO | | NULL | |
+------------+----------+------+-----+---------+----------------+
class Product < ActiveRecord::Base
has_many :product_orders
has_many :orders, through: :product_orders
end
class ProductOrder < ActiveRecord::Base
belongs_to :product
belongs_to :order
end
Product.first.orders
has_and_belongs_to_manyの実装
例
./bin/rails g model Article title
./bin/rails g model Tag name
./bin/rails g create_join_table_article_tag article tag
mysql> desc articles_tags;
+------------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+------------+---------+------+-----+---------+-------+
| article_id | int(11) | NO | | NULL | |
| tag_id | int(11) | NO | | NULL | |
+------------+---------+------+-----+---------+-------+
class Article < ActiveRecord::Base
has_and_belongs_to_many :tags
end
Article.first.tags
アソシエーションのオプション
dependent
inverce_of
delegate
touch
どっちつかうの問題2
ポリモーフィック
vs
STI(単一テーブル継承)
目的:共通するインターフェイスを便利に使いたい
決して同じフィールドがあるから共通化しよ~ではない
ポリモーフィック
役割ごとに分割する。操作が違うことがある場合
STI
役割はわりと同じで、一部のデータ構造だけが違う場合
個人的には、MySQLなどを使っている場合はテーブル継
承はRailsの世界で解決しているので、進んで選ぶことは
ないかなーと。本当に必要かどうかは見極め重要。
ポリモーフィック実装例
./bin/rails g model Camera iso
./bin/rails g model Pc cpu
./bin/rails g model Review reviewable:references{polymorphic}:index message
mysql> desc cameras;
+------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| iso | varchar(255) | YES | | NULL | |
| created_at | datetime | NO | | NULL | |
| updated_at | datetime | NO | | NULL | |
+------------+--------------+------+-----+---------+----------------+
mysql> desc reviews;
+-----------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra
+-----------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment
| reviewable_id | int(11) | YES | | NULL |
| reviewable_type | varchar(255) | YES | MUL | NULL |
class Camera < ActiveRecord::Base
has_many :reviews, as: :reviewable
end
class Review < ActiveRecord::Base
belongs_to :reviewable, polymorphic: true
end
c = Camera.create(iso:3200)
c.reviews.create(message: "hoge")
mysql> select * from reviews;
+----+---------------+-----------------+---------+---------------------+-----
| id | reviewable_id | reviewable_type | message | created_at | upda
+----+---------------+-----------------+---------+---------------------+-----
| 1 | 1 | Camera | hoge | 2016-04-05 17:10:48 | 2016
| 2 | 1 | Pc | piyo | 2016-04-05 17:13:03 | 2016
+----+---------------+-----------------+---------+---------------------+-----
STIの実装例
./bin/rails g model Player name goal:integer homerun:integer type
./bin/rails g model footballer --parent player
./bin/rails g model baseballer --parent player
mysql> desc players;
+------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(255) | YES | | NULL | |
| goal | int(11) | YES | | NULL | |
| homerun | int(11) | YES | | NULL | |
| type | varchar(255) | YES | | NULL | |
| created_at | datetime | NO | | NULL | |
| updated_at | datetime | NO | | NULL | |
+------------+--------------+------+-----+---------+----------------+
class Player < ActiveRecord::Base
end
class Footballer < Player
end
Footballer.create(name: 'hide', goal: 10)
Baseballer.create(name: 'ichiro', homerun: 5)
mysql> select * from players;
+----+--------+------+---------+------------+---------------------+----------
| id | name | goal | homerun | type | created_at | updated_a
+----+--------+------+---------+------------+---------------------+----------
| 1 | hide | 10 | NULL | Footballer | 2016-04-05 17:21:02 | 2016
| 2 | ichiro | NULL | 5 | Baseballer | 2016-04-05 17:21:28 | 2016
+----+--------+------+---------+------------+---------------------+----------
その他時間が余れば
concern
decorator
service
validator
callback
exception
helper

Weitere ähnliche Inhalte

Ähnlich wie Railsモデル設計ケーススタディ

Common schema my sql uc 2012
Common schema   my sql uc 2012Common schema   my sql uc 2012
Common schema my sql uc 2012
Roland Bouman
 
Common schema my sql uc 2012
Common schema   my sql uc 2012Common schema   my sql uc 2012
Common schema my sql uc 2012
Roland Bouman
 
Memcached Functions For My Sql Seemless Caching In My Sql
Memcached Functions For My Sql Seemless Caching In My SqlMemcached Functions For My Sql Seemless Caching In My Sql
Memcached Functions For My Sql Seemless Caching In My Sql
MySQLConference
 
My sql 5.7-upcoming-changes-v2
My sql 5.7-upcoming-changes-v2My sql 5.7-upcoming-changes-v2
My sql 5.7-upcoming-changes-v2
Morgan Tocker
 
WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...
Fabio Franzini
 
Highload Perf Tuning
Highload Perf TuningHighload Perf Tuning
Highload Perf Tuning
HighLoad2009
 

Ähnlich wie Railsモデル設計ケーススタディ (20)

Common schema my sql uc 2012
Common schema   my sql uc 2012Common schema   my sql uc 2012
Common schema my sql uc 2012
 
Common schema my sql uc 2012
Common schema   my sql uc 2012Common schema   my sql uc 2012
Common schema my sql uc 2012
 
MySQLinsanity
MySQLinsanityMySQLinsanity
MySQLinsanity
 
MariaDB 10.5 new features for troubleshooting (mariadb server fest 2020)
MariaDB 10.5 new features for troubleshooting (mariadb server fest 2020)MariaDB 10.5 new features for troubleshooting (mariadb server fest 2020)
MariaDB 10.5 new features for troubleshooting (mariadb server fest 2020)
 
The MySQL SYS Schema
The MySQL SYS SchemaThe MySQL SYS Schema
The MySQL SYS Schema
 
Modern query optimisation features in MySQL 8.
Modern query optimisation features in MySQL 8.Modern query optimisation features in MySQL 8.
Modern query optimisation features in MySQL 8.
 
Curso de MySQL 5.7
Curso de MySQL 5.7Curso de MySQL 5.7
Curso de MySQL 5.7
 
Parallel Query in AWS Aurora MySQL
Parallel Query in AWS Aurora MySQLParallel Query in AWS Aurora MySQL
Parallel Query in AWS Aurora MySQL
 
Memcached Functions For My Sql Seemless Caching In My Sql
Memcached Functions For My Sql Seemless Caching In My SqlMemcached Functions For My Sql Seemless Caching In My Sql
Memcached Functions For My Sql Seemless Caching In My Sql
 
My sql 5.7-upcoming-changes-v2
My sql 5.7-upcoming-changes-v2My sql 5.7-upcoming-changes-v2
My sql 5.7-upcoming-changes-v2
 
Query Optimization with MySQL 5.7 and MariaDB 10: Even newer tricks
Query Optimization with MySQL 5.7 and MariaDB 10: Even newer tricksQuery Optimization with MySQL 5.7 and MariaDB 10: Even newer tricks
Query Optimization with MySQL 5.7 and MariaDB 10: Even newer tricks
 
Fluentd 20150918 no_demo_public
Fluentd 20150918 no_demo_publicFluentd 20150918 no_demo_public
Fluentd 20150918 no_demo_public
 
Datagrids with Symfony 2, Backbone and Backgrid
Datagrids with Symfony 2, Backbone and BackgridDatagrids with Symfony 2, Backbone and Backgrid
Datagrids with Symfony 2, Backbone and Backgrid
 
Instrumenting plugins for Performance Schema
Instrumenting plugins for Performance SchemaInstrumenting plugins for Performance Schema
Instrumenting plugins for Performance Schema
 
MySQL SQL Tutorial
MySQL SQL TutorialMySQL SQL Tutorial
MySQL SQL Tutorial
 
MongoDB user group israel May
MongoDB user group israel MayMongoDB user group israel May
MongoDB user group israel May
 
WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...
 
Confoo 2021 -- MySQL New Features
Confoo 2021 -- MySQL New FeaturesConfoo 2021 -- MySQL New Features
Confoo 2021 -- MySQL New Features
 
MySQL document_store
MySQL document_storeMySQL document_store
MySQL document_store
 
Highload Perf Tuning
Highload Perf TuningHighload Perf Tuning
Highload Perf Tuning
 

Mehr von zaru sakuraba

パフォーマンス計測Ciサービスを作って得た知見を共有したい
パフォーマンス計測Ciサービスを作って得た知見を共有したいパフォーマンス計測Ciサービスを作って得た知見を共有したい
パフォーマンス計測Ciサービスを作って得た知見を共有したい
zaru sakuraba
 

Mehr von zaru sakuraba (14)

WebAssembly と Rust の入口の向かいにある道路のベンチに腰掛けるレベルのさわってみた感想を共有
WebAssembly と Rust の入口の向かいにある道路のベンチに腰掛けるレベルのさわってみた感想を共有WebAssembly と Rust の入口の向かいにある道路のベンチに腰掛けるレベルのさわってみた感想を共有
WebAssembly と Rust の入口の向かいにある道路のベンチに腰掛けるレベルのさわってみた感想を共有
 
Goでこれどうやるの? 入門
Goでこれどうやるの? 入門Goでこれどうやるの? 入門
Goでこれどうやるの? 入門
 
CarrierWaveにちょっと互換あるGCP Storage対応クラス
CarrierWaveにちょっと互換あるGCP Storage対応クラスCarrierWaveにちょっと互換あるGCP Storage対応クラス
CarrierWaveにちょっと互換あるGCP Storage対応クラス
 
パフォーマンス計測Ciサービスを作って得た知見を共有したい
パフォーマンス計測Ciサービスを作って得た知見を共有したいパフォーマンス計測Ciサービスを作って得た知見を共有したい
パフォーマンス計測Ciサービスを作って得た知見を共有したい
 
普通のRailsアプリをdockerで本番運用する知見
普通のRailsアプリをdockerで本番運用する知見普通のRailsアプリをdockerで本番運用する知見
普通のRailsアプリをdockerで本番運用する知見
 
スクラム導入に向けて:スクラムは救世主となるのか?
スクラム導入に向けて:スクラムは救世主となるのか?スクラム導入に向けて:スクラムは救世主となるのか?
スクラム導入に向けて:スクラムは救世主となるのか?
 
GitHub Appsの作り方
GitHub Appsの作り方GitHub Appsの作り方
GitHub Appsの作り方
 
社内ネットワーク改善の過程で分かった物理ゆえの闇と脆弱性そしてネットワークの基礎入門
社内ネットワーク改善の過程で分かった物理ゆえの闇と脆弱性そしてネットワークの基礎入門社内ネットワーク改善の過程で分かった物理ゆえの闇と脆弱性そしてネットワークの基礎入門
社内ネットワーク改善の過程で分かった物理ゆえの闇と脆弱性そしてネットワークの基礎入門
 
Service workerとwebプッシュ通知
Service workerとwebプッシュ通知Service workerとwebプッシュ通知
Service workerとwebプッシュ通知
 
良いプログラマーとは
良いプログラマーとは良いプログラマーとは
良いプログラマーとは
 
スマホフロントエンド最速化手法
スマホフロントエンド最速化手法スマホフロントエンド最速化手法
スマホフロントエンド最速化手法
 
正規表現勉強会
正規表現勉強会正規表現勉強会
正規表現勉強会
 
今さらながらRSpecに入門してみた
今さらながらRSpecに入門してみた今さらながらRSpecに入門してみた
今さらながらRSpecに入門してみた
 
少し未来のコードレビュー
少し未来のコードレビュー少し未来のコードレビュー
少し未来のコードレビュー
 

Kürzlich hochgeladen

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 

Kürzlich hochgeladen (20)

Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 

Railsモデル設計ケーススタディ