sacmax
sacmax

Reputation: 15

Is there a better way of overriding devise controller in rails

I have to populate a field in my db when a new user signs-up.But this field is not to be filled by the user, instead will be populated by the application in the db. Here is what i tried:

  1. Added the extra field(investorId) in the migration file.
  2. Overridden the devise controller:

    def create
    super
    if @user.save
    @user.investorId = @user.id + X---> some number
    @user.save
    end
    end

Though it is working fine, but I want to know if there are better ways of doing it since I am doing it for the first time.

Thanks, Sachin

Upvotes: 0

Views: 57

Answers (2)

SacWebDeveloper
SacWebDeveloper

Reputation: 2812

If you need to generate a value before you create a record, you can use the before_create or after_create callbacks on the model.

User < ActiveRecord::Base
  after_create :generate_investor_id

  private

  def generate_investor_id
    reload
    investor_id = "#{self.id}something"
    update_attribute(:investor_id, investor_id)
  end
end

Upvotes: 1

LHH
LHH

Reputation: 3323

Don't override your devise controller, there is no benefit of doing this. Simply put the below logic in your after_create callback -

User < ActiveRecord::Base
  after_create :create_investor_id

  private

    def create_investor_id
      self.update_column(:investor_id, id+some_number)
    end
end

Upvotes: 1

Related Questions