Upgrade to Pro — share decks privately, control downloads, hide ads and more …

chou

 chou

akatsukinewgrad

January 08, 2021
Tweet

More Decks by akatsukinewgrad

Other Decks in Programming

Transcript

  1. "DUJWF3FDPSE σʔλϕʔεͷϨίʔυΛϞσϧԽ  %#ͷΧϥϜϞσϧͷଐੑ  0CKFDU3FMBUJPOBMNBQQJOH 03. class ApplicationRecord <

    ActiveRecord::Base end class User < ApplicationRecord end user = User.find(1) puts user.id # 1 puts user.name # Taro id name 1 Taro 2 Jiro 3 Saburo Usersテーブル M-V-C 
  2. Ϟσϧͷؔ࿈ΛදݱͰ͖Δ id name 1 Taro 2 Jiro 3 Saburo usersテーブル

    id user_id address 1 1 Tokyo 2 1 Yokohama 3 2 Saga 4 2 Chiba 5 3 Tokyo user_addressesテーブル 例えば、1対他のassociation class User < ApplicationRecord has_many :user_addresses end class UserAddress < ApplicationRecord belongs_to :user end user1 = User.find(1) user1.user_addresses # <UserAddress id: 1>, <UserAddress id: 2> user1.user_addresses.map(&:address) # ['Tokyo', ‘Yokohama'] 
  3. Կ͕ى͖Δ  ؔ࿈σʔλ͕ඞཁ  %#ͰΫΤϦΛ࣮ߦͯ͠ σʔλΛऔಘ user1 = User.find(1) user1.user_addresses

    # <UserAddress id: 1>, <UserAddress id: 2> SELECT "user_addresses".* FROM "user_addresses" WHERE "user_addresses"."user_id" = 1 
  4. ϧʔϓ͢ΔͱʢҰ൪యܕతͳέʔεʣ users = User.all users.each do |user| puts user.user_addresses end

    SELECT "users".* FROM "users" SELECT "user_addresses".* FROM "user_addresses" WHERE "user_addresses"."user_id" = 1 SELECT "user_addresses".* FROM "user_addresses" WHERE "user_addresses"."user_id" = 2 SELECT "user_addresses".* FROM "user_addresses" WHERE "user_addresses"."user_id" = 3 N 1 + ΫΤϦ͕͍ͬͺ͍ൃߦ͞ΕΔ ήʔϜαʔόʔͰ/͕࣌ʹઍ୯Ґ 
  5. / ໰୊ΛͲ͏ղܾ͢Δʁ جຊతͳղܾํ๏ɿQSFMPBE͢Δ ͋ͱͰඞཁʹͳΔෳ਺ͷϨίʔυΛࣄલʹ·ͱΊͯऔ͓ͬͯ͘͜ͱ ൒෼Ҏ্ͷέʔε͸͜ΕͰղܾͰ͖Δʂ users = User.includes(:user_addresses).all SELECT "users".*

    FROM "users" SELECT "user_addresses".* FROM "user_addresses" WHERE "user_addresses"."user_id" IN (1,2,3) SELECT "users".* FROM "users" SELECT "user_addresses".* FROM "user_addresses" WHERE "user_addresses"."user_id" = 1 SELECT "user_addresses".* FROM "user_addresses" WHERE "user_addresses"."user_id" = 2 SELECT "user_addresses".* FROM "user_addresses" WHERE "user_addresses"."user_id" = 3 before after