Rails has_many构建方法作为多态资源

时间:2011-12-07 20:41:05

标签: ruby-on-rails ruby build foreign-keys has-many

class OrganizationModuleAttachment < ActiveRecord::Base
  belongs_to :attachable, :polymorphic => true
end

class Document < ActiveRecord::Base
  has_many :organization_module_attachments, :as => :attachable, :dependent => :destroy

  def organization_module_attachment_ids=(values)
    (values || []).each_with_index do |organization_module_id, index|
      organization_module_attachments.build(:organization_module_id => organization_module_id, :attachable_type => "Document", :position => index + 1)
    end
  end
end

form.html.haml:
= f.select :organization_module_attachment_ids, options_for_select((@organization_modules || []).collect { |a| [a.name, a.id] }, (@document.organization_modules || []).collect { |a| a.id }), {}, { :class => "multiselect", :multiple => true }

所以在文档类中我正在尝试构建organization_module_attachments。提交表单时,我在创建组织模块附件时出错。我认为rails假定附件上的外键是:document_id,实际上它是多态的,因此是:attachable_id。如果我在构建方法中显式设置:attachable_id,它可以正常工作。

我尝试了很多东西,并且搜索了几天没有运气。有谁知道怎么做?

0 个答案:

没有答案