定義模型作爲
Class Jobpost
belongs_to :resource, :polymorphic => true, :dependent => :destroy
accepts_nested_attributes_for :resource
def resource_attributes=(params = {})
self.resource = spec_type.constantize.new unless self.resource
self.resource.attributes = params.select{|k| self.resource.attribute_names.include?(k) || self.resource.class::ACCESSOR.include?(k.to_sym)}
end
end
class Freelancer
has_one :jobpost, :as => :resource
end
字段添加到Jobpost爲創建字段(RESOURCE_ID:整數,RESOURCE_TYPE:字符串)
#jobposts table
t.references :resource, :polymorphic => true
的視圖
= form_for(@jobpost, :url => jobposts_path, :method => :post) do |f|
= fields of Jobpost
= f.fields_for :resource, build_resource('freelancer') do |freelancer|
= fields of Freelancer
的Jobpost助手爲
module JobpostsHelper
def build_resource(klass)
klass = "{klass.capitalize}"
object = eval("#{klass}.new")
if @jobpost.resource.class.name == klass
object = @jobpost.resource
end
return object
end
end
使用JavaScript來顯示子類別(自由職業者等)被點擊的鏈接,當自由職業者的領域。當提交表單時,所有子類別的所有字段都會被提交,但它們會在'resource_attributes ='方法中被過濾掉。
我認爲這個選項,但我提供了3個鏈接不下拉列表... – NJF