本文介绍了具有多态性的belongs_to的accepts_nested_attributes_for的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想与accepts_nested_attributes_for
建立多态关系.这是代码:
I would like set up a polymorphic relation with accepts_nested_attributes_for
. Here is the code:
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
推荐答案
刚刚发现Rails不支持这种行为,所以我想出了以下解决方法:
Just figured out that rails does not supports this kind of behavior so I came up with the following workaround:
class Job <ActiveRecord::Base
belongs_to :client, :polymorphic=>:true, :autosave=>true
accepts_nested_attributes_for :client
def attributes=(attributes = {})
self.client_type = attributes[:client_type]
super
end
def client_attributes=(attributes)
self.client = type.constantize.find_or_initialize_by_id(attributes.delete(:client_id)) if client_type.valid?
end
end
这使我可以像这样设置表单:
This gives me to set up my form like this:
<%= f.select :client_type %>
<%= f.fields_for :client do |client|%>
<%= client.text_field :name %>
<% end %>
不是确切的解决方案,但是这个想法很重要.
Not the exact solution but the idea is important.
这篇关于具有多态性的belongs_to的accepts_nested_attributes_for的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!