使用validate显示错误消息

时间:2013-12-05 23:03:22

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.2 ruby-on-rails-3.1 ruby-on-rails-4

我在屏幕上显示错误信息时遇到了问题。

我有一个名为Issue的课程,这里有几个附件。

没有型号/ issue_attachment, 我正在检查文件以确定它们是否受支持。在不支持文件名的情况下,我在屏幕上显示数字 1 (仅用于测试,我会改进)。

只有它没有显示" LOL"屏幕上。我知道我可以进行验证并在model / issue_attachment上显示错误消息,但在这种情况下我需要这样做。

class IssueAttachment < ActiveRecord::Base
  belongs_to :issue, counter_cache: :attachments_count

  has_attached_file :attachment, :url => '/system/:issue_attachment_directory/:filename'

  validates_attachment_size :attachment, :less_than => 10.megabytes, :message =>    I18n.t('errors.messages.issue_attachment_file_size_html', :max => '10 MB')
  validate :suspitious_attachment


def suspitious_attachment
 if ends_with? '.bat', '.com', '.exe', '.src', '.cmd'
   1
 end
 1
end

private

def ends_with?(*args)
  args.each do |arg|
    return true if attachment.path.ends_with? arg
  end
  false
  end  
end

在模特/问题中,我有:

class Issue < ActiveRecord::Base
 ...
accepts_nested_attributes_for :attachments, allow_destroy: true
validate :suspitious_attachment02

private

def suspitious_attachment02
  attachments.all.each do |attachment|
    if attachment.suspitious_attachment == 1
      errors.add(:attachments, "LOL")
    end 
  end
end

有人可以帮助我吗?它可以这样做吗?

谢谢=]

解决方案

在model / issue.rb中,要更改

def suspitious_attachment02
  attachments.all.each the | attachment |

def suspitious_attachment02
  attachments.each the | attachment |

0 个答案:

没有答案