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

Let's get started with Ruby && Rails Tips

Let's get started with Ruby && Rails Tips

【オフライン開催】Omotesando.rb #96
https://omotesandorb.connpass.com/event/313860/

Takumi Shotoku

April 04, 2024
Tweet

More Decks by Takumi Shotoku

Other Decks in Technology

Transcript

  1. ࣗݾ঺հ • ໊લ: ਖ਼ಙ ޼(aka: ਆ଎) • GitHub: @sinsoku (ը૾ӈ্)

    • Twitter: @sinsoku_listy (ը૾ӈԼ) • ޷͖ͳݴޠ: Rust ! , Ruby " • Railsྺ: 8೥͘Β͍ 2
  2. ActiveRecordͷ loaded? ؔ࿈ΛطʹಡΈࠐΜͰ͍Ε͹ true Λฦ͢ɻ user = User.first user.posts.loaded? #=>

    false user.posts #=> SELECT "posts".* FROM "posts" WHERE "posts"."user_id" = ? user.posts.loaded? #=> true 17
  3. ۩ମతͳϢʔεέʔε index @users = User.includes(:posts).all # rbs: Hash[User, ActiveSupport::TimeWithZone] @posted_at_per_user

    = @users.to_h do |user| [user, user.last_posted_at] end show @user = User.find(params[:id]) @posted_at = @user.last_posted_at 18
  4. User#last_posted_at ͷ࣮૷ྫ # rbs: () -> ActiveSupport::TimeWithZone? def last_posted_at if

    posts.loaded? posts.max_by(&:created_at)&.created_at else posts.maximum(:created_at) end end 19
  5. pick ΍ pluck ʹ΋஫ҙ class User has_many :tags def tag_names

    tags.pluck(:name) end end # pluck Λ࢖͍ͬͯΔͨΊɺeager loading ͕ޮ͔ͳ͍ user = User.includes(:tags).first #=> User Load (0.0ms) SELECT "users".* FROM "users" ORDER BY "users"."id" ASC LIMIT ? [["LIMIT", 1]] #=> Tag Load (0.1ms) SELECT "tags".* FROM "tags" WHERE "tags"."user_id" = ? [["user_id", 1]] user.tag_names #=> Tag Pluck (0.0ms) SELECT "name" FROM "tags" WHERE "tags"."user_id" = ? [["user_id", 1]] 20
  6. ActiveRecordͷcount, size, lengthͷҧ͍ • count ৗʹ SELECT COUNT(*) Λൃߦ͢Δ •

    size ؔ࿈ΛಡΈࠐΜͰ͍ͳ͍৔߹ʹ SELECT COUNT(*) Λൃߦ͢Δ • length ؔ࿈ΛಡΈࠐΜͰ͍ͳ͍৔߹ʹ SELECT(*) Λൃߦ͢Δ 21
  7. ·ͱΊ • ! ϧϏʔΛങͬͨ • " loaded? ͷ঺հ • "

    count, size, lengthͷҧ͍ͷ঺հ 23