#119 Session Based Model

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.

# 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

# controllers/application.rb
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

<% if user_session.can_edit_comment? comment %>
<p><%= link_to "Edit", edit_comment_path(comment) %></p>
<% end %>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值