Rails link_to Method! — Helper Method ไหนที่ใช้บ่อยที่สุดในทุก Rails Apps
แตทำงานยังไง? มาเรียนรู้ link_to และ Options ต่างๆ ที่นี่!
First... link_to ทำอะไร? Website ทำงานได้เพราะ Links ระหว่าง Pages — ไป Page To Page ได้
Plain HTML สร้าง Link:
Improve Your Ruby Skills
แตใน Rails long แบบนี้:
<%= link_to "Improve Your Ruby Skills", "/ruby-book" %>
ทำไม? ใช้ Routes ใน Rails — อยาก用 _path Methods ทำ Target (href) ของ Link — link_to ทำให้ง่าย ไม่ต้อง Interpolate
หมายถึง:
Improve Your Ruby Skills
ตอนนี้: มาดู Optional Arguments ที่มีประโยชน์ที่สุด
Rails link_to Options & Arguments
Argument แรก = Text บน Link — Argument ที่ 2?
คือ URL ที่ Link ไป — Hardcode ได้ แตส่วนใหญ่用 Rails Model หรือ _path Method — Rails Figure Out ตาม Conventions
ตัวอย่าง:
<%= link_to "Improve Your Ruby Skills", book_path(@book) %>
หรือ: <%= link_to "Improve Your Ruby Skills", @book %>
รู้ไหนใช้ไหน?
- Singular Form = Specific Resource (book)
- Plural Form = Collection (books)
ตัวอย่าง:
# Plural <%= link_to "All Books", books_path %> # Singular <%= link_to "Edit Book", edit_book_path(@book) %>
ดู Routes (rake routes) ช่วย — Column 1 มี Name (เช่น edit_book) ใส่ _path ใช้ใน Links ได้
Delete Link พร้อม Confirmation
2 Options 有用:
- confirm
- disable_with
ตัวอย่าง:
<%= link_to "Delete Book", @book, method: "delete", { confirm: "Are you sure?", disable_with: "Processing..." } %>
Default Action ของ Link = GET Request — อยาก用 "DELETE" ต้อง ระบุชัดเจน
แต link ไป Previous Page อยากยังไง? ลองนี้: <%= link_to "Back", :back %>
ใช้ Custom CSS Classes & HTML Attributes
ทำ Links ต่างออกไปด้วย CSS — เช่น:
<%= link_to "Get More Books", books_path, class: "index-link" %>
สมมติ CSS นี้: .index-link { color: blue; padding: 10px; }
ต้องการ HTML Attributes เพิ่ม (เช่น "id") ใส่หลัง Link Text และ URL
สร้าง Query Params & Anchor Links
Option อีกตัว有用: สร้าง Links พร้อม Query Parameters และ Anchors
ทำไมถึงช่วย? เข้าถึง Additional Data จาก Controller หลัง User Click ได้
ตัวอย่าง!
อยาก URL แบบนี้: "/search?q=all" — ทำแบบนี้: <%= link_to "Search ALL", search_path(q: "all") %>
และ URL นี้: "/books#programming" — ทำแบบนี้: <%= link_to "Programming Books", books_path(anchor: "programming") %>
รวมกับ URL Helpers (_path / _url) link_to ให้ Flexibility ครบ
Link ไป Images
หลายคนไม่รู้ link_to รับ Optional Block — Enable Complex Scenarios
เช่น Link ไป Image:
<%= link_to books_path do %> <%= image_tag "Book Collection" %> <% end %>
Block Content = Linking Text, Image, หรือ HTML Element ใดๆ ที่อยากให้ Clickable
Summary (สรุป)
คุณเรียนรู้ link_to ใน Rails!
ถ้าชอบบทความนี้ ได้ Copy หนังสือ Ruby ของผม Super-charge Ruby Skills และ Support Work
ขอบคุณที่อ่าน 🙂