sadaf2605
sadaf2605

Reputation: 7540

How to change rails model object variable names that holds object of another model

Say I have this model and associated schema defined.

class Memory < ActiveRecord::Base
    belongs_to :memory_slot
end

class MemorySlot < ActiveRecord::Base
    has_many :memories
end

Now typically it let me can access memory slots of Memory via @memory.memory_slot.name. But I want to access it via different method like @memory.supporting_memory_slot.name. What is the best way I can do that?

Upvotes: 1

Views: 366

Answers (2)

Pavan
Pavan

Reputation: 33542

If you can change your model association like this

class Memory < ActiveRecord::Base
    belongs_to :supporting_memory_slot, :class_name => 'MemorySlot', :foreign_key => 'supporting_memory_slot_id'
end

then you can do something like this

@memory.supporting_memory_slot.name

Note: In this case,you must generate a new migration to add supporting_memory_slot_id to your memories table

Upvotes: 2

Arslan Ali
Arslan Ali

Reputation: 17802

You won't need any new migration, you can use the previous memory_slot_id, and still can change the name like following:

class Memory < ActiveRecord::Base
  belongs_to :supporting_memory_slot, class_name: 'MemorySlot', foreign_key: 'memory_slot_id'
end

class MemorySlot < ActiveRecord::Base
  has_many :memories
end

This way, if you had any records saved previously, they will work in the current scenario as well. But if you generate a new migration, the old records saved will not be accessible, because they were used using the foreign_key as memory_slot_id.

Upvotes: 3

Related Questions