我正在尝试对用户在白天对特定帖子进行评论的数量设置限制。我在Post模型中实现了以下(成功)以限制他们可以创建的帖子数量。
class Post < ActiveRecord::Base
validate :daily_limit, :on => :create
def daily_limit
# Small limit for users who just sign up
if author.created_at >= 14.days.ago
if author.created_posts.today.count >= 4
errors.add(:base, "Exceeds Your Daily Trial Period Limit(4)")
end
else
if author.created_posts.today.count >= author.post_limit_day
errors.add(:base, "Exceeds Your Daily Limit")
end
end
end
end
但是,当我尝试在我的评论模型中添加类似的限制时
class PostComment < ActiveRecord::Base
validate :daily_limit, :on => :create
belongs_to :post, :counter_cache => true
belongs_to :user
def daily_limit
# Small limit for users who just sign up
if user.posted_comments.today.count >= 2
errors.add(:base, "Exceeds Your Daily Trial Period Limit(4)")
end
end
end
我遇到了undefined method 'posted_comments' for nil:NilClass
错误。我不相信我的user_id正确传递到我的模型中,以便使用user.posted_comments.today.count>=2
我在post_comments控制器中的创建操作如下:
class PostCommentsController < ApplicationController
def create
@post = Post.find(params[:post_id])
@post_comment = @post.post_comments.create(post_comment_params)
@post_comment.user = current_user
if @post_comment.save
redirect_to @post
else
flash[:alert] = "Comment Not Added"
redirect_to @post
end
end
end
和我被黑的用户模型如下:
class User < ActiveRecord::Base
has_many :created_posts, class_name: 'Post', :foreign_key => "author_id",
dependent: :destroy
has_many :posted_comments, class_name: 'PostComment', :foreign_key =>"user_id", dependent: :destroy
end
感谢。
答案 0 :(得分:1)
您在&#34;创建&#34;之后分配用户在你的控制器
@post_comment = @post.post_comments.create(post_comment_params)
@post_comment.user = current_user
试试这个:
@post_comment = @post.post_comments.build(post_comment_params)
@post_comment.user = current_user