ubuntu, ror, jQuery, css, website memo
太嫩, 沒啥心得, 用來紀錄每天學的
2008年11月19日 星期三
session,model,railscast
http://railscasts.com/episodes/119-session-based-model
# 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 %>
<%= link_to "Edit", edit_comment_path(comment) %>
<% end %>
沒有留言:
張貼留言
較新的文章
較舊的文章
首頁
訂閱:
張貼留言 (Atom)
沒有留言:
張貼留言