Product、Image、Postの3つのモデルがあります。Post と Product には多くの画像があり、これはポリモーフィックです。画像を含む新しい製品または投稿を作成しようとすると、次のようになります。
IOError (closed stream):
app/controllers/posts_controller.rb:18:in `create'
面白いことに、画像なしで製品または投稿を作成し、戻ってモデルを編集すると、問題なく画像をアップロードできます。
class Product < ActiveRecord::Base
belongs_to :category
has_many :images, as: :imageable, :dependent => :destroy
accepts_attachments_for :images, attachment: :file
has_many :line_items
end
class Post < ActiveRecord::Base
validates_presence_of :title, :body
has_many :images, as: :imageable, :dependent => :destroy
accepts_attachments_for :images, attachment: :file
end
class Image < ActiveRecord::Base
belongs_to :imageable, polymorphic: true
attachment :file
end
class PostsController < ApplicationController
load_and_authorize_resource
def index
@posts = Post.all.order("created_at desc")
end
def show
@post = Post.find(params[:id])
end
def new
@post = Post.new
end
def create
@post = Post.new(post_params)
if @post.save
redirect_to @post
else
render 'new'
end
end
def edit
@post = Post.find(params[:id])
end
def update
@post = Post.find(params[:id])
if @post.update_attributes!(post_params)
redirect_to @post
else
render "edit"
end
end
private
def post_params
params.require(:post).permit(:title, :subtitle, :body, images_files: [])
end
end
ここは /posts/_form.html.slim です
.form
= form_for @post do |post|
= post.text_field :title
= post.label :title
= post.text_field :sub_title
= post.label :subtitle
div
- @post.images.each do |image|
.photo
= attachment_image_tag(image, :file, :fill, 150, 150)
div
= check_box_tag "images_ids[]", image.id, false, :id => "image_#{image.id}"
label remove
div
= post.attachment_field :images_files, multiple: true
label Photos
.edit-section
label Body
= post.text_area :body, :class => "edit", :style => "display: none"
.field.editable[contenteditable="true" data-field-id="body"]
- if @post.body?
= @post.body.html_safe
- else
p
| Body goes here
.button-box
= post.submit :class => "button primary"
= link_to "Cancel", :back, :class => "button cancel"