Rails 自定义操作验证
我想知道是否有一种方法可以在自定义操作上使用 Rails 验证。
例如,我想做这样的事情:
validates_presence_of :description, :on => :publish, :message => "can't be blank"
我创建和保存基本验证,但有很多事情我不想预先要求。即,他们应该能够在不验证所有字段的情况下保存准系统记录,但是我的控制器和模型中有一个自定义的“发布”操作和状态,使用时应该进行验证以确保记录为 100%
上面的示例没有不起作用,有什么想法吗?
更新:
我的状态机看起来像这样:
include ActiveRecord::Transitions
state_machine do
state :draft
state :active
state :offline
event :publish do
transitions :to => :active, :from => :draft, :on_transition => :do_submit_to_user, :guard => :validates_a_lot?
end
end
我发现我可以添加防护,但我仍然希望能够使用 Rails 验证,而不是在自定义方法上完成这一切。
I would like to know if there's a way to use rails validations on a custom action.
For example I would like do something like this:
validates_presence_of :description, :on => :publish, :message => "can't be blank"
I do basic validations create and save, but there are a great many things I don't want to require up front. Ie, they should be able to save a barebones record without validating all the fields, however I have a custom "publish" action and state in my controller and model that when used should validate to make sure the record is 100%
The above example didn't work, any ideas?
UPDATE:
My state machine looks like this:
include ActiveRecord::Transitions
state_machine do
state :draft
state :active
state :offline
event :publish do
transitions :to => :active, :from => :draft, :on_transition => :do_submit_to_user, :guard => :validates_a_lot?
end
end
I found that I can add guards, but still I'd like to be able to use rails validations instead of doing it all on a custom method.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对我来说,这看起来更像是业务逻辑而不是模型验证。几年前,我参与了一个项目,我们必须在其中发表文章,许多业务规则就是在那时执行的。
我建议您执行类似 Model.publish() 的操作,该方法应强制执行所有业务规则以便发布项目。
一种选择是运行自定义验证方法,但您可能需要向模型添加一些字段。这是一个例子 - 我假设你的模型被称为文章
在这个例子中,客户端代码应该调用
an_article.publish
并且当调用article.save
时它会这样做其余的自动完成。这种方法的另一个大好处是您的模型将始终保持一致,而不是取决于调用的操作。That looks more like business logic rather than model validation to me. I was in a project a few years ago in which we had to publish articles, and lots of the business rules were enforced just at that moment.
I would suggest you to do something like Model.publish() and that method should enforce all the business rules in order for the item to be published.
One option is to run a custom validation method, but you might need to add some fields to your model. Here's an example - I'll assume that you Model is called article
In this example, the client code should call
an_article.publish
and whenarticle.save
is invoked it will do the rest automatically. The other big benefit of this approach is that your model will always be consistent, rather than depending on which action was invoked.如果您的“发布”操作将某种状态字段设置为“已发布”,那么您可以这样做:
或者,如果每个状态都有自己的方法
If your 'publish' action sets some kind of status field to 'published' then you could do:
or, if each state has its own method