为什么我的验证正在运行?

时间:2013-01-03 08:04:19

标签: ruby-on-rails validation paperclip

我正在创建具有附件的对象。我是通过分裂一个真实的领域(可能是我的问题的真正来源)伪造领域。另外,这些工作正常,但是当我附加文件时,我的验证似乎在我的控制器逻辑运行之前运行,并且我最终得到如下错误:

undefined method `match` for nil:Nil at line ...

回形针是否触发了验证?如何在验证运行之前将其关闭,或使我自己的逻辑运行?

我的模型看起来像这样:

attr_accessible :zipcode
has_attached_file :attachment

#this is the line referred to by the error message
validates :zipcode, format: { with: /a_meaningful_regex_here/i}

def initialize
  zipcode = '-'
end
def set_zipcode(params={})
  zipcode = "#{params[:zipcode1]}-#{params[:zipcode2]}"
end
def zipcode1
  zipcode.split('-')[0]
end
def zipcode2
  zipcode.split('-')[1]
end

我的表单如下:

<%= form_for @foo do |f| %>
  <%= f.file_field :attachment %>
  <%= text_field_tag  :zipcode1,@foo.zipcode1%> - 
  <%= text_field_tag  :zipcode2,@foo.zipcode2%>
  <%= f.submit %>
<% end %>

我的控制器看起来像这样:

def create
  @foo = Foo.new(params[:foo])
  @foo.set_zipcode(params)
  if @foo.save
    redirect_to @foo
  else
    render action: 'new'
  end
end

1 个答案:

答案 0 :(得分:0)

尝试类似:

before_validation(:on => :zipcode) { set_zipcode }