Rails validates_length_of行为不端

时间:2010-04-28 16:15:38

标签: ruby-on-rails ruby validation

我有一个我正在添加验证的rails模型,而且我似乎从一个验证器中遇到了一些奇怪。

所以这是我正在使用的表(来自schema.rb):

  create_table "clients", :force => true do |t|
    t.string   "name"
    t.string   "last_contact"
    t.integer  "contacting_agent"
    t.date     "last_payment_date"
    t.float    "last_payment_amt"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.string   "office"
    t.integer  "client_id"
  end

我有一个普通的观点,有:

<%= error_messages_for 'client' %>
<h1>New Client</h1>
<% form_for @client do |new| %>

<table id='newform'>
 <tr>
  <th>Field</th>
  <th>Value</th>
 </tr>
 <tr>
  <td>
   ID
  </td>
  <td>
   <%= new.text_field :client_id %>
  </td>
 </tr>
 <tr>
  <td>
   Name
  </td>
  <td>
   <%= new.text_field :name %>
  </td>
 </tr>
 <tr>
  <td>
   Office
  </td> 
  <td>
   <%= new.select :office, $offices %>
  </td>
 </tr>
 <tfoot>
  <tr>
   <td>
    <%= image_submit_tag "/images/icons/save_32.png" %>
    <a href="/clients/new" title="Clear"><%= image_tag "/images/icons/close_32.png" %></a>
   </td>
   <td>
    &nbsp;
   </td>
  </tr>
 </tfoot>
</table>

<% end %>

和我简陋的模特

class Client < ActiveRecord::Base
  validates_length_of :client_id, :in => 5..7
  validates_uniqueness_of :client_id
  validates_presence_of :name, :client_id
end

所以踢我屁股的部分是模型中的第一个验证。

validates_length_of :client_id, :in => 5..7

如果我前往浏览器并加载视图(/ clients / new),我输入client_id和名称,选择一个办公室,然后点击提交。验证程序未正确提取:client_id,因为它始终会因“太短”或“太长”错误消息而失败。

踢球者是它会给我“太短”错误,直到我尝试大约11个字符,然后在12个字符,我得到“太长”。所以11是“太短”的门槛,即使该范围应该是“5..7” - 但有时而不是“太长”的消息,它实际上将验证并插入记录,但记录它插入对于“client_id”具有完全不同的数字,并且它总是相同的,尽管validates_uniqueness_of

我认为正在发生的是:client_id,而不是验证实际字段client_id,它试图获取对象id,并验证它。至少,这是我唯一能想到的。

  Parameters: {"x"=>"13", "y"=>"14", "authenticity_token"=>"removed", "client"=>{"name"=>"test345", "client_id"=>"12345678", "office"=>"US10"}}

以上,从服务器日志中,对:client_id

的验证为“太短”

所以,请问,有什么方法可以纠正这种怪异吗? (注意:我尝试了validates_length_of "client_id", :in => 5..7,但绝对没有验证)

1 个答案:

答案 0 :(得分:1)

client_id列是整数。 validates_length_of使用size方法查找字段的长度,对于整数,它只给出变量的大小(以字节为单位),前11个字符可能为4,12 +为8

如果你真的需要client_id为整数并验证长度,你可以使用:

validates_inclusion_of :client_id, :in => 10000..9999999, :message => "should be between 5 and 7 characters"
相关问题