Rails - 需要 current_user 信息的自定义验证
我遇到了一个非常困难的 Rails 问题,我想寻求帮助.情况是这样的:
I'm having a very difficult rails problem and i thought to ask for some help. The situation is like this :
我正在为我的用户模型使用 Restful 身份验证.现在,用户有一个名为gold"的字段,它是一个数值.还有一个名为 Book 的模型是使用脚手架创建的.
I'm using restful authentication for my User model. Now, user has a field named 'gold' that is a numeric value. There is another model named Book that has been created using scaffolding.
我想做的很简单,但我看不到这样做的方法.我想添加一些验证,如果用户的金币不是,比如说 100,他们将无法创建新书条目(从脚手架标准视图).
What i want to do is simple, yet i cannot see a way of doing it. I want to add some validation where if the user's gold is not, let's say 100, they cannot create a new book entry(from the scaffolding standard view).
现在的问题是我需要 current_user 信息才能从我的模型中验证这一点.我需要它来获取用户 ID 并因此获取他们的金币数量.我找不到这样做的好方法(如果有的话).
Now the problem is that i need current_user information in order to validate this from my model. I need that in order to get the user id and therefore get their gold amount as well. I cannot find a good way (if any) to do that.
另一个想法是从控制器中做到这一点.但是,标准的if @book.save"块并不允许我插入自己的错误消息(在脚手架创建中):
Another thought was doing that from a controller. However, the standard "if @book.save" block does not really allow me to insert my own error messages (inside scaffold create) :
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
现在,我无法输出该消息并中止新书的保存.我试过将我自己的错误添加到 base 中,但它被清除了(我猜是保存后).我对这种情况很困惑,我已经搜索了几个小时但没有结果.
Now, i cannot output that message and abort the save of the new book as well. I've tried adding my own error to base, but it was cleared out(after save i guess). I'm quite confused with the situation and i've been searching around for a couple of hours with no results.
如果有人可以帮忙,请这样做,你会免除我很多麻烦:)
If anybody can help with that, please do so, you would spare me lots of trouble :)
感谢阅读!
您可以为 Book
定义一个 :user_gold
虚拟属性,将其设置在您拥有的控制器中访问 current_user
,然后将其合并到您的 Book
验证中.
You could define a :user_gold
virtual attribute for Book
, set it in the controller where you have access to current_user
and then incorporate that into your Book
validation.