【问题标题】:unable to upload images using rails paperclip and nested form无法使用 rails 回形针和嵌套表单上传图像
【发布时间】:2013-09-11 17:52:55
【问题描述】:

这是我的表单

<%= 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个字段只插入了null,图片未上传。

编辑 4

如果我添加 &lt;%= f.fields_for :post_details do |uploads| %&gt; 它本身不显示嵌套表单

【问题讨论】:

  • 请在控制台中检查显示的错误。可能有拼写错误
  • @SabyasachiGhosh 你能否检查我的编辑 1 以获取控制台日志
  • 我猜帖子详情模型中存在一些白名单属性问题,或者您可以在帖子详情模型中设置 att_accessable 请检查
  • @SabyasachiGhosh 检查我的edit-2
  • 这个新参数是白名单属性还是作为attribute_accessable

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


【解决方案1】:

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

attr_accessible :post_detail_attributes

另一个问题是@post.post_details.build 可能属于您的新操作而不是创建。

【讨论】:

    【解决方案2】:

    试试这个,

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-14
      • 2014-08-24
      • 1970-01-01
      • 1970-01-01
      • 2016-01-22
      • 1970-01-01
      • 1970-01-01
      • 2018-08-25
      相关资源
      最近更新 更多