0

我对回形针有一个奇怪的问题。以下是我验证此问题的撬动会话。当我上传文件时,回形针附件构造正确,但是当我将对象保存在数据库中时,数据丢失了!!

我尝试上传的图像已成功上传到正确的位置。

     7:     flash[:notice] = "Item created"
     8:     item = Item.new(strong_params)
     9:     item.user = current_user
    10:     item.photo = params[:item][:photo]
    11:     item.save
 => 12:     binding.pry
    13:     redirect_to item
    14:   end
    15:   def strong_params
    16:     params.require(:item).permit!
    17:   end
    pry(#<ItemsController>)> item.errors.messages
=> {}
pry(#<ItemsController>)> dbItem = Item.find(item.id)
=> #<Item id: 2, user_id: 1, name: "", description: "", created_at: "2013-10-16 23:49:06", updated_at: "2013-10-16 23:49:06", photo_file_name: nil, photo_content_type: "image/jpeg", photo_file_size: 11763, photo_updated_at: "2013-10-16 23:49:06">
pry(#<ItemsController>)> dbItem.photo_file_name == item.photo_file_name
=> false
pry(#<ItemsController>)> puts dbItem.photo_file_name         

=> nil
pry(#<ItemsController>)> puts item.photo_file_name
item.jpg
=> nil
pry(#<ItemsController>)> 

有问题的控制器操作

 def create
    flash[:notice] = "Item created"
    item = Item.new(strong_params)
    item.user = current_user
    item.photo = params[:item][:photo]
    item.save
    binding.pry
    redirect_to item
  end
  def strong_params
    params.require(:item).permit!
  end

项目表

 create_table "items", force: true do |t|
    t.integer  "user_id"
    t.string   "name"
    t.string   "description"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.string   "photo_file_name"
    t.string   "photo_content_type"
    t.integer  "photo_file_size"
    t.datetime "photo_updated_at"
  end

物品型号

class Item < ActiveRecord::Base
  belongs_to :user
  attr_accessor :photo_file_name

  has_attached_file :photo,
    :url => "/assets/photos/:id/:style/:basename.:extension",
    :path => ":rails_root/public/assets/items/:id/:style/:basename.:extension"
  validates_attachment_presence :photo
end
4

1 回答 1

1

我怀疑您attr_accessor :photo_file_name正在覆盖 Paperclip 中的某些内容,因为它希望这是一个 activerecord 字段。

于 2013-10-17T23:41:20.707 回答