Home > Mobile >  Update Column name with default values if value doen't exist in rails
Update Column name with default values if value doen't exist in rails

Time:09-19

I have added a module in rails concern to update two attributes with a default value.

But not able to do it. Could someone please explain it?

module DefaultValueForCreateAndUpdateUserid
  extend ActiveSupport::Concern
    before_save do
      self.create_userid = 'f' if !self.create_userid?
      self.last_updt_userid = 'f' if !self.last_updt_userid?
    end
  end
end

But it is giving this error:

NoMethodError: undefined method `before_save' for DummyValueForCreateAndUpdateUserid:Module

CodePudding user response:

You can use included and also ||= to check and assign attribute

module DefaultValueForCreateAndUpdateUserid
  extend ActiveSupport::Concern

  included do
    before_save :assign_absent_attributes
  end

  def assign_absent_attributes
    self.create_userid ||= 'f'
    self.last_updt_userid ||= 'f'
  end
end

And than include this concern in the model

class MyModel < ApplicationRecord
  include DefaultValueForCreateAndUpdateUserid
end

CodePudding user response:

This should fit your needs.

  • Related