Rails 2.3.8验证不能从控制台工作(有效?总是返回true)

时间:2011-11-08 19:54:05

标签: ruby-on-rails validation

我最近将rails应用程序从rails 2.3.3更新到2.3.8并遇到了这样的问题:所有模型验证在浏览器中都能正常工作,但在使用 .valid?来自控制台的方法。这发生在我的所有模特身上。 例如,我的公司模型包含:

class Company < Content
...

 # Validation

  before_validation     :ensure_token_existance

  validates_presence_of :name,
                        :address,
                        :employee_count,
                        :category_ids,
                        :region_ids,
                        :phone,
                        :email,
                        :if => Proc.new { |company| company.step?(1) },
                        :message => "required field"

  validates_presence_of :description,
                        :if => Proc.new { |company| company.step?(2) },
                        :message => "required field"

  after_update :cache_sweeper

...

现在从控制台测试公司实例的验证:

$ script/console 
Loading development environment (Rails 2.3.8)
>> c = Company.new
=> #<Company id: nil, account_id: nil, name: nil, description: nil, employee_count: nil, logo_file_name: nil, logo_content_type: nil, logo_file_size: nil, logo_updated_at: nil, created_at: nil, updated_at: nil, moderation: nil, token: nil, expired_at: nil, address: nil, phone: nil, fax: nil, email: nil, site: nil, delta: true, position: nil, major_company: false, wizard_step: 0, manager_id: nil, org_form: "", robots: nil, language: nil>
>> c.valid?
=> true
>> c.errors
=> #<ActiveRecord::Errors:0x105004848 @errors=#<OrderedHash {}>, @base=#<Company id: nil, account_id: nil, name: nil, description: nil, employee_count: nil, logo_file_name: nil, logo_content_type: nil, logo_file_size: nil, logo_updated_at: nil, created_at: nil, updated_at: nil, moderation: "draft", token: "mYoXPgNYwxBmdCTI", expired_at: nil, address: nil, phone: nil, fax: nil, email: nil, site: nil, delta: true, position: nil, major_company: false, wizard_step: 0, manager_id: nil, org_form: "", robots: nil, language: nil>>
>> c.save
=> true
>> c.save!
=> true

我已查看http://guides.rubyonrails.org/v2.3.8/activerecord_validations_callbacks.html#when-does-validation-happen

  

以下方法会触发验证,并将对象保存到   仅当对象有效时才使用数据库:

create
create!
save
save!
update
update_attributes
update_attributes!
     

如果记录是爆炸版本(例如保存!)会引发异常   无效。非爆炸版本不:save和update_attributes   返回false,创建和更新只返回对象。

有人可以帮我弄清楚这里有什么问题吗? =)

1 个答案:

答案 0 :(得分:1)

您的验证取决于公司处于某个步骤。您永远不会在控制台中设置此属性。如果你尝试会发生什么:

c = Company.new
c.step = 1
c.valid?

我只是猜测step?方法只对属性step进行了相等性测试。如果没有,请执行任何操作,以便您的模型满足step?(1)