I'm a Ruby on Rails / jQuery web developer. Follow me at @sikachu

เจออะไรใน Rails 3: ใส่ flash message ลงไปใน redirect_to ได้เลย

January 20th, 2010 Posted in Ruby, Ruby on Rails

เจออะไรใน Rails 3 เป็นสกู๊ปพิเศษสำหรับนำเสนอสิ่งใหม่ๆ ที่จะมีเพิ่มขึ้นมาใน Ruby on Rails 3.0

ความเป็นมา

ปกติแล้วใน Rails 2 ถ้าเราต้องการที่จะตั้งค่า flash message ก่อนที่จะทำการ redirect เราจำเป็นทีจะต้องตั้งค่ามันก่อนที่จะเรียก redirect_to เช่น

class UsersController < ApplicationController
  def create
    @user = User.new(params[:user])
    if @user.save
      flash[:notice] = "User has been successfully created."
      redirect_to users_path
    else
      render :action => "new"
    end
  end
end

เพิ่ม flash message ใน redirect_to

ใน Rails 3 นั้น คุณสามารถใช้ :flash ในการตั้งค่า flash message ได้เลย เช่น

redirect_to users_path, 
    :flash => { :notice => "User has been successfully created." }

และเพื่อเพิ่มความสะดวกในการตั้งค่า flash message ที่ใช้บ่อยๆ เช่น flash[:notice] และ flash[:alert] ทาง Rails ก็ได้เพิ่ม options ขึ้นมาอีกสองตัวคือ :notice และ :alert ทำให้เรายังสามารถเขียนโค้ดด้านบนได้เป็น

redirect_to users_path, 
    :notice => "User has been successfully created."

จะเห็นได้ว่า options ที่เพิ่มเข้ามานี้จะช่วยทำให้ความซ้ำซ้อนของโค้ดนั้นลดไปได้อีกจุดหนึ่ง และทำให้เราเขียนโค้ดได้สบายขึ้นนั่นเอง

ปล. โดยส่วนตัวแล้วผมใช้ flash[:notice] และ flash[:error] แต่คิดว่าหลังจากได้เห็น feature นี้ ทั้ง flash[:notice] และ flash[:alert] คงจะกลายเป็น convention ของ Rails ไปอย่างแน่นอน

Sorry, comments for this entry are closed at this time.