ครับมีโอกาสได้ทำพวก Dynamic menu มาเลยเขียนมาแบ่งปันกันนะครับ เพื่อมีประโยชน์กันบ้าง ก็เริ่มกันเลยดีกว่า คือที่ผมต้องการทำคือการเลือกชุดคำถาม จากนั้นให้มีคำถามในชุดนั้นออกมา ซึ่งจะมีรูปการเรียกใช้ดังโค้ดต่อไปนี้
![]()
โค้ดในส่วของหน้า view : index.html.erb
ชุดคำถาม :
<%= collection_select(nil,:question_set_id, @question_sets,:id,:title,
{:prompt => “เลือกชุดคำถาม”},
{:onchange => “#{remote_function(:loading => “$(‘indicator’).show()”,:complete => “$(‘indicator’).hide()”,:failure => “alert(‘There was an error. ‘)”,:url => {:action => “update_question”},
:with => “‘question_set_id=’+value”)}”}) %>
<%= image_tag “indicator.gif”, :id => ‘indicator’, :style => ‘display:none’ %>
เลือกคำถาม :<div id=”questions” class=”a”><%= render :partial => ‘questions’,
bject => @questions %></div>
<%= submit_tag “ตกลง” %>
โดยคำสั่งที่ใช้จะเป็น collection_select (nil,:question_set_id, @question_sets,:id,:title,) ในส่วน @question_sets
นั้น คือ array ของ object ของ questions ส่วน question_set_id นั้นเป็น id ของ collection นี้ ส่วนของ :title คือให้โชว์ title ออกมา
:prompt เป็นชื่อใน field ที่จะเลือกนั้น ส่วน onchange นั้นมีไว้ขึ้นมาเพื่อเวลาเรียกใช้จะได้มีรูป นาฬิกาหมุนเพื่อแสดงว่ากำลังทำงานอยู่
โดยเราจะต้องมี image tag ไว้เพื่อที่จะสั่ง update field นั้น โดยเมื่อทำการเลือกในชุดคำถามนั้น จะไปเรียกใช่้ action update_question
และส่วนสุดท้ายคือ ส่วนของคำถาม render :partial => ‘questions’,
bject => @questions
จะไว้ render คำถามที่อยู่ในชุดคำถามนั้น โดยที่จะอ้างผ่าน tag div
โค้ดในส่วน controller :index
@question_sets = QuestionSet.all
@questions = Question.all
controller :update_question
@question_set = QuestionSet.find(params[:question_set_id])
questions = @question_set.questions //to find question in set
render :update do |page|
page.replace_html ‘questions’,:partial => ‘questions’,
bject => questions
questions.destroy
end
โค้ดในส่วนของ _question.html.erb
<%= collection_select(nil, :questions,questions, :id, :title,
{:prompt => “เลือกคำถาม”}) %>
ครับเท่านี้เราก็จะได้ Dynamic menu กันแล้ว
หวังว่าคงมีประโยชน์ในการทำบ้างนะครับ (^^)
Last 5 posts by liopopo
- เปลี่ยนรูปแบบ font สี ในการเขียนโปรแกรมใน netbeans กันเถอะ - January 7th, 2010
- การใช้ DOM popup ใน rails - January 6th, 2010
- การใช้ Ajax ใน RoR - November 26th, 2009
- การสร้าง tab ใน rails ด้วย Rails Widget - November 6th, 2009
- การใช้ will_paginate มาช่วยในการสร้างเว็บ - October 4th, 2009
