Ruby on rails RubyonRails-将用户限制为一定数量的数据库条目

Ruby on rails RubyonRails-将用户限制为一定数量的数据库条目,ruby-on-rails,ruby,devise,Ruby On Rails,Ruby,Devise,我想限制用户可以添加到数据库中的记录数量 我不确定“Rails”是怎么做的 我正在使用Desive and Think创建自定义验证方法,但您无法从模型中访问当前用户,这是不正确的 如何从控制器执行此操作,同时仍向用户返回错误消息 我有这个 validate :post_count def post_count current = current_user.posts.count limit = current_user.roles.first.posts.count

我想限制用户可以添加到数据库中的记录数量

我不确定“Rails”是怎么做的

我正在使用Desive and Think创建自定义验证方法,但您无法从模型中访问
当前用户
,这是不正确的

如何从控制器执行此操作,同时仍向用户返回错误消息

我有这个

 validate :post_count

  def post_count
    current = current_user.posts.count
    limit = current_user.roles.first.posts.count

    if current > limit
      errors.add(:post, "Post limit reached!")
    end
  end

但这并不是正确的方法,因为让当前用户进入该模型会很麻烦。您可以这样做:

class User < ActiveRecord::Base
  has_many :domains
  has_many :posts, through: :domains

  def post_limit
    roles.first.posts.count
  end
end

class Domain < ActiveRecord::Base
  belongs_to :user
  has_many :posts
end

class Post < ActiveRecord::Base
  belongs_to :domain
  delegate :user, to: :domain
  validate :posts_count_within_limit, on: :create

  def posts_count_within_limit
    if self.user.posts(:reload).count >= self.user.post_limit # self is optional
      errors.add(:base, 'Exceeded posts limit')
    end
  end
end
class用户=self.user.post#limit,则self是可选的
错误。添加(:base,“超出了帖子限制”)
结束
结束
结束

基于。

也许您可以在创建新帖子时进行验证。然后你可以计算出与当前正在创建的帖子的创建者相同的用户创建了多少帖子(从而避开了当前用户的问题),并将其与该用户的限制进行比较。好的,我如何在模型中检查'limit=current_user.roles.first.posts.count'。请参见Backpackerh的答案,但我建议将代码移动到User类上的某个方法来检索限制。这看起来不错,但我需要从db中获取当前用户限制?只需将
替换为
User.roles.first.posts.count
(假设这是db中的限制)。我建议将限制的检索移动到用户对象上的方法,而不是在验证中内联。(即,在验证中将self.user.roles.first.posts.count替换为self.user.post\u limit,并将该代码放在用户类的post\u limit方法中。好的,这正是我想要的,但我意识到它不起作用,因为我在用户和post之间有另一个模型…它是这样的
用户有很多:域,域有很多:posts
。我尝试了
delegate:user,:to=>:在域模型中发布
,但它似乎不起作用?我得到了错误
未定义的方法
user'`@MaxRose Collins Perfect!:)