ruby-on-rails-4rails-adminafter-create

adding an after_create method in Rails Admin


I'm using Rails 4.1 and Rails Admin. I have a Project Model with the following fields: name: slug: project_number.

When I create a new project in the admin I want the project_number to be created automatically using the id and the slug. Like this: self.project_number = self.slug + '_' + self.id

I was trying to do this in the project controller using an after_create method, I'm now realising that rails_admin is not hitting my controller. Can anyone point me in the right direction on how to do this? Would this be a rails_admin custom action?


Solution

  • This is because you need grab after_create in the model.

    /models/project.rb

    class Project < ActiveRecord::Base
    
      after_create :generate_project_number
    
    
      def generate_project_number
        self.project_number = "#{slug}_#{id}"
      end
    
    end
    

    In this way when you create a new Project (form anywhere) project_number will be saved as "slug_id"

    [29] pry(main)> Project.create!(slug: 'hello_world')
    => #<Project id: 3, slug: "hello_world", project_number: "hello_world_3", created_at: "2016-05-11 23:00:19", updated_at: "2016-05-11 23:00:19">