Rails booleans bug?

时间:2010-10-31 04:45:59

标签: ruby-on-rails activerecord ruby-on-rails-3

我在Rails中处理布尔值时有一个相当神秘的问题,这里是如何重现:

  1. rails new boolean_bug
  2. rails generate model用户验证:boolean
  3. 有了这个,你应该有一个带有用户模型的空项目。

    3内部boolean_bug / app / models / user.rb

    class User < ActiveRecord::Base
     before_save :set_false
     attr_accessible :verified                 
    
     private  
       def set_false  
         self.verified = false
       end
    end
    

    4在控制台中知道重现:

    $rails -v 
    Rails 3.0.1
    
    $ rails console --sandbox
    ruby-1.9.2-p0 > User.create!
    ActiveRecord::RecordNotSaved: ActiveRecord::RecordNotSaved
    from /Users/dpalacio/.rvm/gems/ruby-1.9.2-p0/gems/activerecord-3.0.1/lib/active_record/persistence.rb:56:in `save!'
    from /Users/dpalacio/.rvm/gems/ruby-1.9.2-p0/gems/activerecord-3.0.1/lib/active_record/validations.rb:49:in `save!'
    from /Users/dpalacio/.rvm/gems/ruby-1.9.2-p0/gems/activerecord-3.0.1/lib/active_record/attribute_methods/dirty.rb:30:in `save!
    

    5将self.verified = false更改为self.verified = 0

    6再次进入控制台

    ruby-1.9.2-p0 > User.create!
     => #<User id: 1, verified: false, created_at: "2010-10-31 04:23:13", updated_at: "2010-10-31 04:23:13"> 
    

    所以关键是使用false保存不起作用,但是真的,1,0工作,这是一个错误吗?或者我做错了什么?

1 个答案:

答案 0 :(得分:6)

抱歉没有一个rails bug,实际上是因为before_filter从赋值中返回false,因此活动记录不会保存。