วันพฤหัสบดี, มิถุนายน 21, 2550

อ่าน Agile Web Development with Rails ( 6 )

ตอนที่แล้วเรายุ่งอยู่กับหลังบ้านของ depot คราวนี้มาจัดหน้าบ้านบ้างครับ

เราจะสร้าง controller ใหม่ขึ้นมาอีกอันหนึ่ง ให้ชื่อว่า store
ruby script/generate controller store index
index ที่แปะท้ายเพิ่มมาจากที่เราคุ้นเคยนั้นมีเพื่อบอกให้ Rails สร้าง action ชื่อ index ใส่ไว้ใน controller นี้ด้วยครับ

การทำอย่างนี้ นอกจาก Rails จะสร้าง app/controllers/store_controller.rb แล้ว ยังสร้าง app/views/store/index.rhtml ให้เราด้วยเลย

ที่ app/controllers/store_controller.rb เราจัดการแก้โค้ดให้เป็นดังนี้
class StoreController < ApplicationController
def index
@products = Product.find_products_for_sale
end
end

แล้วเราก็ไปแก้ product model เพิ่ม mothod ชื่อ find_products_for_sale เข้าไปดังนี้
def self.find_products_for_sale
find(:all, :order => "title" )
end

คำสั่ง find จะคืนค่ากลับมาเป็น array ของข้อมูลจาก product ที่มีเงื่อนไข :all (เอาหมด) และเรียงลำดับตามฟิลด์ "title" ที่ระบุโดย :order => "title"

คราวนี้ไปจัดการกับ app/views/store/index.rhtml ให้เป็นอย่างนี้

Your Pragmatic Catalog
<% for product in @products -%>
<div class="entry" >
<img src="<%= product.image_url %>" />
<%= h(product.title) %>
<%= product.description %>
<%= number_to_currency(product.price) %>
<%= button_to "Add to Cart" , :action => :add_to_cart, :id => product %>
</div>
<% end %>


คำสั่ง h() ใช้ถอด HTML Elements ออกจากข้อความ
- ที่อยู่นำหน้า %> ใช้ บอกให้ไม่ต้องขึ้นบรรทัดใหม่หลังคำสั่งนี้

ส่วนเจ้า add_to_cart นี่เราจะไปคุยกันตอนหน้าครับ

ไม่มีความคิดเห็น: