在rails 4中的回调before_create中,不设置值为false

时间:2016-04-19 10:04:54

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

我有一个模特

module Interspire
  class InterspireLead < ActiveRecord::Base
    before_create :update_contactable

    def update_contactable
      self.contactable = false #contactable datatype is boolean
    end
  end
end

但是当我创建一个对象时。

a = Interspire::InterspireLead.create(:email => "abc@gmail.com")
a.valid?
  #=> true
a.errors.full_messages
  #=>[]
a.save
  #=>  ROLLBACK

如何解决此问题?

4 个答案:

答案 0 :(得分:1)

update_contactable方法中返回true:

def update_contactable
  self.contactable = false #contactable datatype is boolean
  true
end

答案 1 :(得分:0)

您的回调需要是私密的。 (编辑:这是错误的。这不是必需的!)

来自文档的示例:

class Subscription < ActiveRecord::Base
  before_create :record_signup

  private
    def record_signup
      self.signed_up_on = Date.today
    end
end

答案 2 :(得分:0)

您需要使用其他回调

before_save :update_contactable if: new_record?

不是

before_create

答案 3 :(得分:0)

false会阻止创建对象而不会出现任何错误 正如扎强所说:

    def update_contactable
    self.contactable = false
    1 == 1
    end