Rails - 需要current_user信息的自定义验证

时间:2010-11-21 01:10:15

标签: ruby-on-rails ruby validation

我有一个非常困难的轨道问题,我想要求一些帮助。情况是这样的:

我正在为我的用户模型使用restful身份验证。现在,用户有一个名为“gold”的字段,它是一个数字值。还有另一个名为Book的模型,它是使用脚手架创建的。

我想做的很简单,但我看不到这样做的方法。我想添加一些验证,如果用户的黄金不是,让我们说100,他们不能创建一个新的书籍条目(从脚手架标准视图)。

现在问题是我需要current_user信息才能从我的模型中验证这一点。我需要它来获取用户ID,因此也获得他们的黄金数量。我找不到一个好方法(如果有的话)。

另一个想法是从控制器那样做。但是,标准的“if @ book.save”块实际上不允许我插入我自己的错误消息(在scaffold创建中):

if not User.has_the_needed_gold(current_user, 100)
  flash[:goldError] = 'You do not have the needed gold to create this book.'
#end


respond_to do |format|
  if @book.save
    flash[:notice] = 'Book was successfully created.'
    format.html { redirect_to(@book) }
    format.xml  { render :xml => @book, :status => :created, :location => @book }
  else
    format.html { render :action => "new" }
    format.xml  { render :xml => @book.errors, :status => :unprocessable_entity }
  end
end

现在,我无法输出该消息并中止新书的保存。我已经尝试将自己的错误添加到基础,但它已被清除(保存后我猜)。我对这种情况很困惑,我一直在寻找几个小时而没有结果。

如果有人可以提供帮助,请这样做,你会给我带来很多麻烦:)

Thanx阅读!

2 个答案:

答案 0 :(得分:2)

您可以为:user_gold定义Book虚拟属性,将其设置在您有权访问current_user的控制器中,然后将其合并到Book验证中。< / p>

答案 1 :(得分:2)

验证时查看用户。用户查找可能已被ActiveRecord缓存,因此这不会影响性能。尝试这样的事情:

class Book

  validate :check_gold

  def check_gold
    user = User.find(self.user_id)
    self.errors.add(:user_id => "#{user.name} doesn't have enough gold!") if user.nil? or (user.gold < 100)
  end
end