Adding members to Ruby objects dynamically

If you want to dynamically add a member to a Ruby object, use the hash/array brackets and symbol (:user_id) as shown in the iRb session below. As you can see the dot notation will not work.

>> d = AccessMode.find(1)
=> #<AccessMode id: 1, device_id: 31218, mode: "dialup", timestamp: "2007-12-25 15:52:55">
>> d[:user_id] = 5
=> 5
>> d
=> #<AccessMode id: 1, device_id: 31218, mode: "dialup", timestamp: "2007-12-25 15:52:55">
>> d.user_id
=> 5
>> d.user_id = 6
=> 6
>> d.session_id = 10
NoMethodError: undefined method `session_id=' for #<AccessMode:0x58dace8>
from C:/chirag no backup/haloror/vendor/rails/activerecord/lib/active_record/attribute_methods.rb:251:in `method_missing'
from (irb):23
Share