用于验证目的的动态查找器方法 [英] Dynamic finder methods for validation purposes
问题描述
我使用的是Ruby on Rails 3.0.7,我想在运行时查找一些记录以进行验证,但需要为该finder方法传递一个值。也就是说,在我的班级中,我有以下内容:
I am using Ruby on Rails 3.0.7 and I would like to find some records at run time for validation purposes but passing\setting a value for that finder method. That is, in a my class I have the following:
class Group < < ActiveRecord::Base
validates :relation_id,
:presence => true,
:inclusion => {
:in => ... # Read below for more information about
}
end
如果我将:in
设置为
:in => User.find(1).group_ids
它有效,但我想设置动态-things,而不是下面示例中所述的 1
值。也就是说,我想执行以下操作,以便以某种方式将< test_value>
传递给模型:
it works, but I would like to set "some-dynamic-things" for the finder method instead of the 1
value stated below in the example. That is, I would like to do something like the following in order to pass to the model a <test_value>
in someway:
class Group < < ActiveRecord::Base
validates :relation_id,
:presence => true,
:inclusion => {
:in => User.find(<test_value>).group_ids
}
end
可能吗?如果是这样,我该如何将值传递给常量?
Is it possible? If so, how can I pass the value to the constant?
PS:要知道,我试图这样做是为了将一些逻辑从控制器移到
P.S.: Just to know, I am trying to make that in order to move some logic from the controller to the model.
推荐答案
我推断您要执行的操作是强制执行仅作为成员的用户一组可以保存它。在这种情况下,您的行为应保留在控制器中。
I'm inferring that what you're trying to do is enforce something like "Only users who are members of a group can save it." If that's the case, you have behavior that should stay in the controller.
您的模型无法访问当前会话,添加此逻辑将阻止您执行以下操作:将来将模型用于其他用途。例如,您将永远无法从与用户无关的批生产或维护工作中保存组。
Your model doesn't have access to the current session, and adding this logic will prevent you from using your model for other things in the future. For example, you'd never be able to save a group from a batch or maintenance job that wasn't associated with a user.
如果您确实要执行此操作您可以将 current_user
类级别变量放在 User
对象中,并将其设置在 before_filter中
...
If you really want to do this you could put a current_user
class level variable in the User
object and set it in a before_filter
...
class ApplicationController
before_fitler :set_current_user
def set_current_user
User.current_user = #however you get your user in your controllers
end
end
class User
@@current_user
end
class Group
validates :user_in_group
def user_in_group
return true unless User.current_user #if we don't have a user set, skip validation
User.current_user.group_ids.include? self.id
end
end
这篇关于用于验证目的的动态查找器方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!