I'm using Active Record outside of rails and I have two AR classes similar to below:
class Building < ActiveRecord::Base
has_many :rooms
serialize :current_room, Room
and
class Room < ActiveRecord::Base
belongs_to :building
I had originally migrated the database tables to have the current_room column be declared as a :room
instead of a :binary
, which worked, but made my db schema unusable due to the unknown type, and potentially would make my implementation non database independent. (using sqlite3, haven't tried another yet)
When I changed the table column type to :binary
from :room
, I started getting a "undefined method" error when attempting to change the current_room variable as I navigate the building from room to room. The error looks like this in irb, where d is a building object:
irb(main):006:0> d.current_room = d.rooms.first
NoMethodError: undefined method `gsub' for #<Room:0x1f6c260>
from C:/Ruby192/lib/ruby/gems/1.9.1/gems/activemodel-3.1.1/lib/active_model/attribute_methods.rb:385:in `method_missing'
from C:/Ruby192/lib/ruby/gems/1.9.1/gems/activerecord-3.1.1/lib/active_record/attribute_methods.rb:60:in `method_missing'
from C:/Ruby192/lib/ruby/gems/1.9.1/gems/activerecord-3.1.1/lib/active_record/connection_adapters/sqlite_adapter.rb:24:in `binary_to_string'
from C:/Ruby192/lib/ruby/gems/1.9.1/gems/activerecord-3.1.1/lib/active_record/connection_adapters/column.rb:84:in `type_cast'
from C:/Ruby192/lib/ruby/gems/1.9.1/gems/activerecord-3.1.1/lib/active_record/attribute_methods/dirty.rb:89:in `field_changed?'
from C:/Ruby192/lib/ruby/gems/1.9.1/gems/activerecord-3.1.1/lib/active_record/attribute_methods/dirty.rb:63:in `write_attribute'
from C:/Ruby192/lib/ruby/gems/1.9.1/gems/activerecord-3.1.1/lib/active_record/attribute_methods/write.rb:14:in `current_room='
from (irb):6
from C:/Ruby192/bin/irb:12:in `<main>'
I presume it is because the object attribute isn't treating it like a Room object, which is understandable, but I thought the serialize method solved that issue. d.current_room.class
and d.rooms.first.class
both return Room as the object class, as well. Is there a way to have this work properly without overwriting the assignment methods?