如何限制用户只能在特定用户的墙上发布一次或两次?我主要想要这样做以限制垃圾邮件。我的墙,型号,视图和控制器的代码如下。我真的不知道如何去做,因为我是铁杆新手,但我知道有时间。现在。我不确定如何实现这样的功能。
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 %>
答案 0 :(得分:2)
您可以创建a custom validator,以确保该用户当天在该人的墙上创建了最多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] %>
页面上显示此内容。