无法使用rails paperclip和嵌套表单上传图像

时间:2013-09-11 17:52:55

标签: ruby-on-rails ruby-on-rails-3 paperclip

这是我在视图中的表单

<%= nested_form_for Post.new,html: {multipart: true},url: {action: :create} do |f| %>
<%= f.text_field :title,placeholder: 'title' %>
<%= f.fields_for :post_detail do |uploads| %>
    <%= uploads.file_field :upload %>
<% end %>
<input type="submit" value="submit" />

这是我的post.rb型号

has_many :post_details
accepts_nested_attributes_for :post_details

这是我的post_detail.rb型号

belongs_to :post
has_attached_file :upload

这是我的post_controller.rb

def create
  @post = Post.new(post_params)
      @post.post_details.build
    if @post.save
      flash[:success] = 'Post added successfully'
      redirect_to root_path
    else
      flash[:error] = 'Post cannot add. Please try again after some time'
      redirect_to action: :new
    end
  end

修改1

这是我能看到的日志

Parameters: {"utf8"=>"✓", "authenticity_token"=>"ZjAnCeF2F1tkDVni96GcihdCd5JkyXHPaTIBjKoLq4s=", "post"=>{"title"=>"test","post_detail"=>{"upload"=>#<ActionDispatch::Http::UploadedFile:0xb2e8208 @tempfile=#<Tempfile:/tmp/RackMultipart20130911-3059-1ahxfek>, @original_filename="Ubuntu-Wallpaper-HD.jpg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"post[post_detail][upload]\"; filename=\"Ubuntu-Wallpaper-HD.jpg\"\r\nContent-Type: image/jpeg\r\n">}}}
Unpermitted parameters: post_detail
Unpermitted parameters: post_detail

修改2

在rails 4中我使用了像这样的attr_accesible

private
  def post_params
    params.require(:post).permit(:title,post_details_attributes:[:upload_file_name,:upload_file_size,:upload_content_type])
  end

编辑3

我在post_details表中手动添加了3列

upload_file_name,upload_file_size and upload_file_content

仅为上述3字段插入空值且图片未上传。

编辑4

如果我添加<%= f.fields_for :post_details do |uploads| %>它没有显示嵌套表单本身

2 个答案:

答案 0 :(得分:0)

这可能不是您唯一的问题,但如果您在当前环境中使用config.active_record.whitelist_attributes = true设置,请将其添加到您的post.rb:

attr_accessible :post_detail_attributes

向我发出的另一个问题是@post.post_details.build可能属于你的新动作,而不是创造。

答案 1 :(得分:0)

试试这个,

private
  def post_params
    params.require(:post).permit(:title,post_details_attributes: [:id, :upload])
  end
相关问题