rails

เรียก controller method จากหน้า view

ปกติแล้วเราจะเรียก method ของ controller จากหน้า view ไม่ได้ วันนี้ได้ดู rails cast ถึงได้รู้ว่าถ้าใช้ method helper_method จะทำให้เราเรียก method นั้นจาก view ได้ เช่น

เราสร้าง method foo แล้วบอกให้ method นี้เป็น helper_method

  1. #blogs_controller.rb
  2. ...
  3. def foo
  4.   "bar"
  5. end
  6. helper_method :foo

จากนั้นทดลองเรียกใช้ในหน้า view

  1. #index.html.erb
  2. ...
  3. <%= foo %>
  4. ...

ตอนเรียกที่หน้า browser จะมีคำว่า bar ขึ้นมา แต่ถ้าไม่ใช้า helper_method มันจะขึ้น

  1. undefined local variable or method `foo' for #<ActionView::Base:0x254fb30>

เพราะ rails หา method foo ไม่เจอ

Rails podcast in Thai ตอน 1

Blog ก่อนหน้านี้ทำให้เข้าใจโครงสร้างของ MVC ชัดเจนมากขึ้น แต่สำหรับ video อันนี้จะเห็นเรื่อง Convention over Configuration ได้มากกว่า

download

customize text_field

ได้แรงบรรดาลใจมาจาก blog ของ PunNeng หน้านี้ พยายามเอามาใช้กับ project ที่ทำงานอยู่แต่ทำยังไงก็ไม่ work ซะที สงสัยเพราะว่าใช้ rails คนละ version กัน ดูใน ruby trac เค้าบอกว่าจะปรับ attribute ของ form_for ใหม่ แต่ตอนนั้นดูแบบคร่าวๆ เพราะไม่รู้ว่าต้องแก้ตรงนี้

สุดท้ายมั่วไปมั่วมาได้ resolution ว่าให้สร้าง file doo_form_helper.rb ไว้ที่ app/helper แบบนี้

  1. module DooFormHelper
  2.   def doo_form_for(record_or_name_or_array, *args, &proc)
  3.      form_for(record_or_name_or_array, *(args << {:builder => DooFormFor}), &proc)
  4.   end
  5.  
  6.   class DooFormFor < ActionView::Helpers::FormBuilder
  7.     def text_field(method, options = {})
  8.           @template.content_tag('p', label(method) + "<br />" + super)
  9.     end
  10.   end
  11. end

จากนั้นที่ _form.html.erb ก็ใช้ doo_form_for แทน

  1. <% doo_form_for(@blog) do |f| %>
  2.  
  3.     <%= f.text_field :title %>
  4.  
  5. <% end %>

ผมลองบน rails 2.0.2 ครับ ไม่รู้ว่า 2.1 จะสามารถใส่ :builder ลงใน form_for เลยได้หรือเปล่า

  1. <% form_for(@blog, :builder => DooFormFor) do |f| %>
  2.  
  3.     <%= f.text_field :title %>
  4.  
  5. <% end %>

ประมาณนี้ แต่ผมชอบแบบใช้ doo_form_for มากกว่า ดูลึกลับดี

ปล. ที่ใช้คำว่า doo ไม่ได้มีความหมายพิเศษครับ แต่เพราะ project ที่ทำงานชื่อว่า dooExpert เลยใช้คำว่า doo นำหน้าน่ะครับ ยังมีต่อครับ >

Rails podcast in Thai

ลองทำ pod cast ของ rails ดู เห็นมีหลายคนบ่นๆ ว่า rails podcast บน internet เป็น rails 1.2 มันเอามาใช้ไม่ได้กับ 2.0 ก็เลยลองทำของ 2.0 ดู ทำมาสองตัวคือ การเขียน blog ด้วย rails กับการเขียน blog แล้วมี comment ด้วย

จริงๆ อยากจะเอาตัวที่เป็น blog ขึ้นมาก่อน แต่ดัน upload ตัวที่เป็น blog + comment เสร็จซะแล้ว ไว้จะเอาอีกตัวขึ้นวันพรุ่งนี้นะครับ



download

Syndicate content