#119 Session Based Model
Jul 21, 2008 | 13 minutes | Models
If you have a lot of logic associated with the data inside a session, you'll need some central location to put this logic. See how to create a session based model in this episode.
- Download:
- source codeProject Files in Zip (93.2 KB)
- mp4Full Size H.264 Video (21.3 MB)
- m4vSmaller H.264 Video (14.2 MB)
- webmFull Size VP8 Video (35.8 MB)
- ogvFull Size Theora Video (31.4 MB)
Resources
models/user_session.rb
class UserSession
def initialize(session)
@session = session
@session[:comment_ids] ||= []
end
def add_comment(comment)
@session[:comment_ids] << comment.id
end
def can_edit_comment?(comment)
@session[:comment_ids].include?(comment.id) && comment.created_at > 15.minutes.ago
end
end
class UserSession def initialize(session) @session = session @session[:comment_ids] ||= [] end def add_comment(comment) @session[:comment_ids] << comment.id end def can_edit_comment?(comment) @session[:comment_ids].include?(comment.id) && comment.created_at > 15.minutes.ago end end
controllers/application.rb
def user_session
@user_session ||= UserSession.new(session)
end
helper_method :user_session
def user_session @user_session ||= UserSession.new(session) end helper_method :user_session
comments_controller.rb
before_filter :authorize, :only => [:edit, :update]
def create
@comment = Comment.new(params[:comment])
if @comment.save
user_session.add_comment(@comment)
flash[:notice] = "Successfully created comment."
redirect_to article_url(@comment.article_id)
else
render :action => 'new'
end
end
private
def authorize
unless user_session.can_edit_comment? Comment.find(params[:id])
flash[:error] = "You are no longer able to edit this comment."
redirect_to root_url
end
end
before_filter :authorize, :only => [:edit, :update] def create @comment = Comment.new(params[:comment]) if @comment.save user_session.add_comment(@comment) flash[:notice] = "Successfully created comment." redirect_to article_url(@comment.article_id) else render :action => 'new' end end private def authorize unless user_session.can_edit_comment? Comment.find(params[:id]) flash[:error] = "You are no longer able to edit this comment." redirect_to root_url end end
rhtml
<% if user_session.can_edit_comment? comment %>
<p><%= link_to "Edit", edit_comment_path(comment) %></p>
<% end %>
<% if user_session.can_edit_comment? comment %> <p><%= link_to "Edit", edit_comment_path(comment) %></p> <% end %>

