##65 Stopping Spam with Akismet

The Railscasts site has been getting a lot of comment spam in the past, but no longer. In this episode I will show you how I solved this problem by using the Akismet web service.
# comments_controller.rb
def create
@comment = Comment.new(params[:comment])
@comment.request = request
if @comment.save
if @comment.approved?
flash[:notice] = "Thanks for the comment."
else
flash[:error] = "Unfortunately this comment is considered spam by Akismet. " +
"It will show up once it has been approved by the administrator."
end
redirect_to episode_path(@comment.episode_id)
else
render :action => 'new'
end
end

def destroy_multiple
Comment.destroy(params[:comment_ids])
flash[:notice] = "Successfully destroyed comments."
redirect_to comments_path
end

def approve
@comment = Comment.find(params[:id])
@comment.mark_as_ham!
redirect_to comments_path
end

def reject
@comment = Comment.find(params[:id])
@comment.mark_as_spam!
redirect_to comments_path
end

# models/comment.rb
before_create :check_for_spam

def request=(request)
self.user_ip = request.remote_ip
self.user_agent = request.env['HTTP_USER_AGENT']
self.referrer = request.env['HTTP_REFERER']
end

def check_for_spam
self.approved = !Akismetor.spam?(akismet_attributes)
true # return true so it doesn't stop save
end

def akismet_attributes
{
:key => 'abc123',
:blog => 'http://railscasts.com',
:user_ip => user_ip,
:user_agent => user_agent,
:comment_author => name,
:comment_author_email => email,
:comment_author_url => site_url,
:comment_content => content
}
end

def mark_as_spam!
update_attribute(:approved, false)
Akismetor.submit_spam(akismet_attributes)
end

def mark_as_ham!
update_attribute(:approved, true)
Akismetor.submit_ham(akismet_attributes)
end
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值