Ruby on Rails,是否可以使模型验证依赖于输入? [英] Ruby on Rails, is it possible to make the model validation dependent on the input?
本文介绍了Ruby on Rails,是否可以使模型验证依赖于输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我的项目中,我有两个模型,Treatment
和 Category
:
class Category <ActiveRecord::Baseattr_accessible :typhas_many :治疗结尾班级待遇
所以在我的处理表单中,用户还可以选择类别(大约 4 个类别):
<%= f.label :category_id %><br/><%= f.collection_select :category_id, Category.find(:all), :id, :typ %>
所以我的问题是,我可以根据表单中选定的类别来验证 Treatment
模型吗?以及如何?
解决方案
可以使用
validate :something_based_on_categorydef something_based_on_category如果 self.category==.....结尾
当您想向模型添加错误时,您也可以使用 errors.add
.
In my project I have two models, Treatment
and Category
:
class Category < ActiveRecord::Base
attr_accessible :typ
has_many :treatments
end
class Treatment < ActiveRecord::Base
belongs_to :patient
belongs_to :category
attr_accessible :content, :day, :typ, :category_typ
end
So in my treatment form the user can also choose the category (around 4 categories):
<div class="field">
<%= f.label :category_id %><br />
<%= f.collection_select :category_id, Category.find(:all), :id, :typ %>
</div>
So my question is, can I make the validation of the Treatment
model dependent on the selected categories in the form? And how?
解决方案
You can use
validate :something_based_on_category
def something_based_on_category
if self.category==.....
end
You also use errors.add
when you want to add an error to the model.
这篇关于Ruby on Rails,是否可以使模型验证依赖于输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文