module StaticAssociation::AssociationHelpers

Public Instance Methods

belongs_to_static(name, opts = {}) click to toggle source
# File lib/static_association.rb, line 53
def belongs_to_static(name, opts = {})
  class_name = opts.fetch(:class_name, name.to_s.camelize)

  self.send(:define_method, name) do
    begin
      foreign_key = self.send("#{name}_id")
      class_name.constantize.find(foreign_key) if foreign_key
    rescue RecordNotFound
      nil
    end
  end

  self.send(:define_method, "#{name}=") do |assoc|
    self.send("#{name}_id=", assoc.id)
  end
end