首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Inherited_resources自定义错误

Inherited_resources自定义错误
EN

Stack Overflow用户
提问于 2012-02-22 03:17:52
回答 1查看 613关注 0票数 1

我有一个带有虚拟属性的模型,用在simple_form中:

代码语言:javascript
复制
class Sms < ActiveRecord::Base
attr_accessor :delayed_send, :send_time_date, :send_time_time

我有/smses/new的表单:

代码语言:javascript
复制
= simple_form_for([:admin, resource]) do |f|
  ...
  .clear
  .field.grid_3
    = f.input :delayed_send, :as => :boolean, :label => "Отложенная отправка на:"
  .clear
  .field.grid_3
    = f.input :send_time_date, :as => :string, :input_html => { :class => 'date_picker' }, :disabled => true, :label => "Дату:"
  .clear
  .field.grid_1
    = f.input :send_time_time, :as => :string, :disabled => true, :label => "Время:", :input_html => { :value => (Time.now + 1.minute).strftime("%H:%M") }
  .clear
  .actions.grid_3
    = f.submit "Отправить"

我想在创建操作中验证SmsesController中的所有虚拟属性,如果无效,则显示错误。但这并不管用:

代码语言:javascript
复制
class Admin::SmsesController < Admin::InheritedResources
def create
  @sms.errors.add(:send_time, "Incorrect") if composed_send_time_invalid?
  super
end

如果我使用inherited_resources,我应该如何添加我的自定义错误?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-02-22 05:11:48

如果没有在控制器中验证的特定原因,则应该在模型中进行验证:

代码语言:javascript
复制
 class Sms < ActiveRecord::Base

  #two ways you can validate:
  #1.use a custom validation routine
  validate :my_validation

  def my_validation
    errors.add(:send_time, "Incorrect") if composed_send_time_invalid?
  end

  #OR 2. validate the attribute with the condition tested in a proc.
  validates :send_time, :message=>"Incorrect", :if=>Proc.new{|s| s.composed_send_time_invalid?} 
end

在控制器中,保存(或调用object.valid?)将触发这些验证运行。然后,您可以在控制器中处理响应,以便在必要时重新呈现操作。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9383723

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档