Search code examples
ruby-on-railsgetter-setterruby-on-rails-4.2instance-methods

Setters from Rails4 InstanceMethods for non-existing fields


I am writing a gem rails4 where i can add dynamic attributes which wont persist in the actual model table, rather it will save in my second table with a reference.

Now i have before_validation to an instance method, where i am trying to set the default value to dynamically added attribute. I am getting the error as

can't write unknown attribute

The code is

self[attr_name.to_sym]=attr_type[:default_value]

Kindly advice on this, how to do setters from the instance method for the non-existing fields.

I have used instance_variable_set for the same in ClassMethods.


Solution

  • You can use attr_accessor method for this purpose in your model.

    class Sample << ActiveRecord::Base  
    
      attr_accessor :attr_name  
    
      #setter method
      def attr_name=(val)
        self[:attr_name] = val
      end  
    
      #getter method
      def attr_name
         self[:attr_name]
      end
    end  
    

    Now, you can call any where instance method like following.

    self[attr_name.to_sym]=attr_type[:default_value]