script/generate scaffold announcement message:text starts_at:datetime ends_at:datetime
script/generate controller javascripts
<!-- layouts/application.html.erb -->
<% unless current_announcements.empty? %>
<div id="announcement">
<% for announcement in current_announcements %>
<p><%=h announcement.message %></p>
<% end %>
<p><%= link_to_remote "Hide this message", :url => "/javascripts/hide_announcement.js" %></p>
</div>
# models/announcement.rb
def self.current_announcements(hide_time)
with_scope :find => { :conditions => "starts_at <= now() AND ends_at >= now()" } do
if hide_time.nil?
find(:all)
else
find(:all, :conditions => ["updated_at > ? OR starts_at > ?", hide_time, hide_time])
end
end
end
# application_helper.rb
def current_announcements
@current_announcements ||= Announcement.current_announcements(session[:announcement_hide_time])
end
# javascripts_controller.rb
def hide_announcement
session[:announcement_hide_time] = Time.now
end
# hide_announcement.js.rjs
page[:announcement].hide
# routes.rb
map.connect ":controller/:action.:format"
#103 Site Wide Announcements
Sometimes you need to display an administrative announcement to every page on the site and give the users the ability to hide the announcement. See how in this episode.
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.