我想与建立多态关系accepts_nested_attributes_for
。这是代码:
class Contact <ActiveRecord::Base
has_many :jobs, :as=>:client
end
class Job <ActiveRecord::Base
belongs_to :client, :polymorphic=>:true
accepts_nested_attributes_for :client
end
当我尝试访问时Job.create(..., :client_attributes=>{...}
给我NameError: uninitialized constant Job::Client
我也遇到了“ArgumentError:无法构建关联 model_name。您是否试图构建多态一对一关联?”的问题。
我找到了解决此类问题的更好方法。您可以使用本机方法。让我们看看 Rails3 中的nested_attributes 实现:
elsif !reject_new_record?(association_name, attributes)
method = "build_#{association_name}"
if respond_to?(method)
send(method, attributes.except(*UNASSIGNABLE_KEYS))
else
raise ArgumentError, "Cannot build association #{association_name}. Are you trying to build a polymorphic one-to-one association?"
end
end
那么实际上我们需要在这里做什么呢?只是在我们的模型中创建 build#{association name} 。我在底部做了完全有效的示例:
class Job <ActiveRecord::Base
CLIENT_TYPES = %w(Contact)
attr_accessible :client_type, :client_attributes
belongs_to :client, :polymorphic => :true
accepts_nested_attributes_for :client
protected
def build_client(params, assignment_options)
raise "Unknown client_type: #{client_type}" unless CLIENT_TYPES.include?(client_type)
self.client = client_type.constantize.new(params)
end
end
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)