我正在开发一个名为 Chapter 的模型,它允许用户使用carrierwave 上传多个图像(+ 一个单独的缩略图)。我创建了一个名为 Attachment 的多态模型来安装上传器。
章节
class Chapter < ActiveRecord::Base
attr_accessible :title, :uploader_comment, :book_id, :attachments_attributes
has_many :comments, as: :commentable
has_many :attachments, as: :attachable
accepts_nested_attributes_for :attachments
belongs_to :book
belongs_to :user
validates :title, presence: true, length: {maximum: 60}
validates :book_id, presence: true
validates :uploader_comment, length: {maximum: 150}
validates :user_id, presence: true
validates :attachments, presence: true
end
附件
class Attachment < ActiveRecord::Base
attr_accessible :chapter_image, :chapter_thumb
belongs_to :attachable, polymorphic: true
mount_uploader :chapter_image, ChapterImageUploader
mount_uploader :chapter_thumb, ChapterThumbnailUploader
validates_presence_of :chapter_image
end
写完上述代码后,我尝试提交表单,但最终得到 “未定义的方法 `chapter_image_will_change!' 为...”错误。经过一番搜索,我在另一篇文章中看到我需要运行一些迁移才能摆脱错误。所以我做了以下。
rails g migration AddAttachmentToChapters
chapter_image:string chapter_thumb:string
bundle exec rake db:migrate
但错误仍然存在。我将包括我的视图页面代码,以防万一它会有所帮助。
新的.html.erb
<div class = "row">
<div class = "span6 offset3">
<%= simple_nested_form_for @chapter, html: {multipart: true},
defaults: {required: false} do |f| %>
<%= render 'shared/error_messages', object: @chapter %>
<%= f.association :book, collection: current_user.books.all,
tag: :book_id, include_blank: false %>
<%= f.input :title, label: 'Chapter title' %>
<%= f.input :uploader_comment %>
<div class = "control-label">
Image file upload
</div>
<%= f.simple_fields_for :attachments do |attachment_form| %>
<%= attachment_form.file_field :chapter_image %>
<%= attachment_form.link_to_remove 'Remove' %>
<% end %>
<%= f.link_to_add 'Add image', :attachments %>
<span class="hint_end">Acceptable file formats: JPG, JPEG, GIF, PNG</span>
<div class = "control-label">
Thumbnail upload
</div>
<%= f.file_field :chapter_thumb %>
<span class="hint_end">Acceptable file formats: JPG, JPEG, GIF, PNG</span>
<%= f.submit "Upload chapter" %>
<% end %>
</div>
</div>
欢迎任何建议/帮助!