我有三个型号Product,Image,Post。帖子和产品有很多图像,这是多态的。当我尝试使用包含的图像创建新产品或帖子时,我得到:
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"