justinfrench/formtastic — pull request #746 by kristianmandrup (2011-11-22 12:56:49+00:00)
Title: Trying to make association reflection handle composite primary keys

Trying to make formtastic play somewhat nice even with composite foreign keys (Oracle use case)

class ProductDescription < ActiveRecord::Base
belongs_to :product, :foreign_key => [:pm_from_option_id, :pm_to_option_id]
...
end

This is my attempt at a hack, but I don't know enough about the formtastic internals.
Here the key simply becomes :product as it detects that the foreign_key is an Array.

module Formtastic
module Helpers
# @private
module Reflection
...

def association_primary_key_for_method(method) #:nodoc:
reflection = reflection_for(method)

if reflection
case association_macro_for_method(method)
when :has_and_belongs_to_many, :has_many, :references_and_referenced_in_many, :references_many
:"#{method.to_s.singularize}_ids"
else
# handle case where foreign key is a composite (Array) fx using 'composite_primary_keys' gem
foreign_key = foreign_key_for reflection
return method.to_sym if !foreign_key || foreign_key.kind_of?(Array)

return foreign_key.to_sym unless foreign_key.blank? || foreign_key.kind_of?(Array)
:"#{method}_id"
end
else
method.to_sym
end
end

protected

def foreign_key_for reflection
return nil if !reflection
return reflection.foreign_key if reflection.respond_to?(:foreign_key)
return reflection.options[:foreign_key] if reflection.respond_to?(:options)
nil
end
end