Carrierwave を使用して、ユーザーが複数の画像 (+ 個別のサムネイル画像) をアップロードできるようにする、Chapter というモデルに取り組んでいます。アップローダをマウントする 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
上記のコードを書いてフォームを送信しようとしたのですが、 「undefined method `chapter_image_will_change!」になってしまいました 。の...」エラー。少し検索した後、エラーを取り除くためにいくつかの移行を実行する必要があることを別の投稿で見ました。だから私は次のことをしました。
rails g migration AddAttachmentToChapters
chapter_image:string chapter_thumb:string
bundle exec rake db:migrate
しかし、エラーはまだ続きます。役立つ場合に備えて、ビュー ページのコードを含めます。
new.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>
アドバイス/ヘルプ歓迎!