0

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

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
4

1 回答 1

0

尝试类似:

before_validation(:on => :zipcode) { set_zipcode }
于 2013-01-03T18:18:37.203 回答