将模型定义为
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
单击 Freelancer 的链接时,使用 javascript 显示子类别(freelancer 等)的字段。提交表单时,所有子类别的所有字段都已提交,但它们在“resource_attributes=”方法中被过滤掉。