Carrierware和nested_forms的问题

时间:2013-06-27 07:25:25

标签: ruby-on-rails carrierwave nested-forms

我正在尝试实施Carrierware和nested_form,以便为我的模型获得多次上传,但遇到了麻烦。

我的模特:

class Idea < ActiveRecord::Base
    attr_accessible :suggested_files_by_owner_attributes 
    has_many :suggested_files_by_owner, :class_name => 'Attachment', :as => :attachable
    has_many :suggested_files, :class_name => 'Attachment', :as => :attachable
    accepts_nested_attributes_for :suggested_files_by_owner
end

我的模特:

class Attachment < ActiveRecord::Base
  attr_accessible :title, :file
  # belongs_to :comment
  belongs_to :attachable, :polymorphic => true
  mount_uploader :file, FileUploader
end

我的架构(我已迁移):

create_table "attachments", :force => true do |t|
    t.datetime "created_at",      :null => false
    t.datetime "updated_at",      :null => false
    t.string   "title"
    t.integer  "attachable_id"
    t.string   "attachable_type"

我迁移了:

class AddFileToIdeas < ActiveRecord::Migration
  def change
    add_column :ideas, :file, :string
  end
end

我的观点:

= nested_form_for @idea, :url => {:action => "update", :controller=>"ideas"}, :html=>{:multipart => true} do |f|
    =f.text_field :title, value: @idea.title
    = f.text_area :description, :size => '30x7', :id => 'description'
    %br 

    = f.label :privacy, "Make Private" 
    = f.check_box :is_private
    %p
    = f.fields_for :suggested_files_by_owner do |a_form|
        = a_form.file_field :file
        = a_form.link_to_remove "Remove"
    = f.link_to_add "Add Attachment", :suggested_files_by_owner


    = f.submit 'Save and Post'

点击提交后发生错误:

undefined method `file_will_change!'

此外,在视图上,当我单击“添加附件”时,会显示两个上传框而不是一个。 任何人都可以帮我弄清楚我的问题吗?

UPDATE 我的错误:

uninitialized constant Idea::SuggestedFilesByOwner

我需要在关联行中添加:class_name => 'Attachment'。见上文

1 个答案:

答案 0 :(得分:1)

如果您忘记在模型的db表中添加列,则会出现

undefined method 'file_will_change!'。您必须将file列添加到Attachment,而不是Idea,因为此列必须添加到包含上传者的模型中:

rails g migration AddFileToAttachments file:string
rake db:migrate