bav ko ten
bav ko ten

Reputation: 532

Dont set value is false in callback before_create in rails 4

I Have a Model

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

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

But when i create a object.

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

How to fix this erorrs?

Upvotes: 1

Views: 454

Answers (4)

Goko Gorgiovski
Goko Gorgiovski

Reputation: 1462

You need to use another callback

before_save :update_contactable if: new_record?

not

before_create

Upvotes: 1

noman tayyab
noman tayyab

Reputation: 365

false stops object from being created without any error as zhaqiang mentioned:

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

Upvotes: 0

Ben Hawker
Ben Hawker

Reputation: 949

Your callback needs to be private. (Edit: This is wrong. It is not a requirement!)

An example from the docs:

class Subscription < ActiveRecord::Base
  before_create :record_signup

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

Upvotes: 0

Hugo Chou
Hugo Chou

Reputation: 96

Return true in your update_contactable method:

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

Upvotes: 1

Related Questions