1

如何将用户限制为每天只能在特定用户的墙上发布一次或两次?我主要想这样做是为了限制垃圾邮件。我的墙、模型、视图和控制器的代码如下。我真的不知道该怎么做,因为我是 Rails 新手,但我知道现在有一些时间。我不确定如何实现这样的功能。

Class UsersController < ApplicationController
def show
 @user = User.find(params[:id])
 @first_name = @user.first_name
 @last_name = @user.last_name
 @wallpost = WallPost.new(params[:wall_post])
 @showwallposts = @user.received_wallposts
end

def create
 @wallpost = WallPost.create(params[:wall_post])
end

楷模

class WallPost < ActiveRecord::Base
 attr_accessible :content, :receiver_id, :sender_id
 belongs_to :receiver, :class_name => "User", :foreign_key => "receiver_id"
 belongs_to :sender, :class_name => "User", :foreign_key => "sender_id"
end


class User < ActiveRecord::Base
 has_many :sent_wallposts, :class_name => 'WallPost', :foreign_key => 'sender_id'  
 has_many :received_wallposts, :class_name =>'WallPost', :foreign_key => 'receiver_id'

在视图中

<%= form_for(@wallpost, :url => {:action => 'create'}) do |f| %>
  <%= f.hidden_field :receiver_id, :value => @user.id %>
  <%= f.hidden_field :sender_id, :value => current_user.id %>    
  <%= f.text_area :content, :class => 'inputbox' %>
  <%= f.submit 'Post', class: 'right btn' %>    
<% end %>
4

1 回答 1

2

您可以创建一个自定义验证器DAILY_LIMIT,以确保该用户当天在该人的墙上创建了最多的帖子:

class SpamValidator < ActiveModel::Validator
  DAILY_LIMIT = 2

  def validate(record)
    if similar_posts_today(record).count >= DAILY_LIMIT
      record.errors[:spam_limit] << 'Too many posts today!'
    end
  end

  def similar_posts_today(record)
    WallPost.where(receiver: record.receiver, sender: record.sender)
            .where("DATE(created_at) = DATE(:now)", now: Time.now)
  end
end

然后将该验证添加到您的WallPost模型中:

validates_with SpamValidator

然后,当尝试创建超出常量中设置的限制的墙帖时,它将失败并出现验证错误。您需要create在控制器中的操作中处理这种情况。处理此问题的一种简单(但在用户体验方面并非最佳)方法是:

def create
  @wallpost = WallPost.new(params[:wall_post])

  flash[:error] = "You've reached the daily posting limit on that wall." unless @wallpost.save

  redirect_to user_path(@wallpost.receiver)
end

这样,它将尝试保存新的墙帖,如果无法保存,它将设置flash[:error]为上面的错误消息。您需要在您的show.html.erb页面上使用<%= flash[:error] if flash[:error] %>.

于 2013-05-27T15:50:04.013 回答