I am developing a Rails 3.2 application with the following models:
class User < ActiveRecord::Base
# Associations
belongs_to :authenticatable, polymorphic
I was able to get this to work by overriding the nested attribute setter.
class Physician
has_one :user, as: :authenticatable
accepts_nested_attributes_for :user
def user_attributes=(attribute_set)
super(attribute_set.merge(authenticatable: self))
end
end
To DRY it up, I moved the polymorphic code to a concern:
module Authenticatable
extend ActiveSupport::Concern
included do
has_one :user, as: :authenticatable
accepts_nested_attributes_for :user
def user_attributes=(attribute_set)
super(attribute_set.merge(authenticatable: self))
end
end
end
class Physician
include Authenticatable
...
end
For has_many
associations, the same can be accomplished with a map
:
class Physician
has_many :users, as: :authenticatable
accepts_nested_attributes_for :users
def users_attributes=(attribute_sets)
super(
attribute_sets.map do |attribute_set|
attribute_set.merge(authenticatable: self)
end
)
end
end
class User
belongs_to :authenticatable, polymorphic: true
validates :authenticatable, presence: true
end
All that said, I think konung's last comment is correct - your example does not look like a good candidate for polymorphism.