views:

234

answers:

2

I'm writing an extension for Spree and I want to remove an existing association.

Given the following code:

class Project < ActiveRecord::Base
  has_one :status
  ...
end

How can I remove the call to has_one :status at runtime? I want to remove the association and associated methods.

A: 

Unfortunately that's a rather complex DSL call that adds lots of methods to the class, you'd have to remove all of those, and it probably wouldn't be worth it.

It's probably easier to create a new class CleanProject, add a Project object to it using composition or inheritance, and then only pass through calls for the parts of Project that you want.

On the other hand, if you meant to ask how to remove a status that has been associated to this project (not remove the fact that statuses are related to projects, but just remove a single status from a single project) you would just call:

status.project_id = nil
status.save
MattMcKnight
A: 

What about leaving it out and only adding it when you need it?

Perhaps you only need the association in a class that is used in a method designed to be executed from a cronjob or batch? Then you might eval the code to bring in the association.

def need_assoc
  eval <<-EOC
    class Project < ActiveRecord::Base
    has_one :status
    ...
    end
  EOC
end

The reason to use eval is to keep the association from being evaluated when classes are loaded.

john