In Rails i am not able to set `attr_accessor` from concern in model level

102 Views Asked by At

I have a concern looking something like

module StrategyConcern
  extend ActiveSupport::Concern

  included do
    attr_accessor :strategy_display_name
  end
end

and i have included it in my model include StrategyConcern but when i try to assign value to that like this

obj["strategy_display_name"] = "test_display_name"

i am getting error

undefined method `strategy_display_name=' for #<Test:0x00007f868e4aa350>

I want that object attribute to access, without getting the mentioned error.

2

There are 2 best solutions below

0
Jakub Górecki On BEST ANSWER

Given that obj is an instance of the model, you should use

obj.strategy_display_name = "test_display_name"

So just get rid of the square brackets ([] which are mainly used when working with arrays and hashes)

You can read more about accessors there for instance: What is attr_accessor in Ruby?

0
Jibran Usman On

You have to use variables in models using the following way:

obj.strategy_display_name = 'test_display_name'
obj.strategy_display_name

The [] operator for active record models is used to access variables holding column values from the database, not instance variables