David
David

Reputation: 825

before_create is not called on model.create

I have this code:

class Project < ActiveRecord::Base
    acts_as_paranoid

    belongs_to :user
    belongs_to :organization
    accepts_nested_attributes_for :organization


    attr_accessible :name, :permalink, :organization_id, :user_id

    validates_length_of :name, :minimum => 4
    validates_presence_of   :permalink
    validates_uniqueness_of :permalink, :case_sensitive => false, :scope => :deleted_at

     
    validates_presence_of :user        
    validates_presence_of :organization

    before_create :generate_permalink

    protected

    def generate_permalink
      binding.pry
      self.permalink = "123456789"
    end    
    
end

When I call in ProjectsController#create

p = Project.new
p.name = "abcdef"
p.save

The app doesn't stop on binding.pry in generate_permalink, and the project is not valid and is not saved because permalink == nil. Why is the generate_permalink method not called?

Upvotes: 3

Views: 2000

Answers (1)

Sampat Badhe
Sampat Badhe

Reputation: 9075

You have to set premalink in before_validation callback. before_create callback is called after validation. and here validation fails so your before_create callback will never call.

Check callback sequence here http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html

Upvotes: 8

Related Questions