Carrierwave将对象数据保存到数据库而不是文件名

时间:2011-03-04 13:34:13

标签: carrierwave

您好 我只是无法找出我的代码有什么问题。我有两个模型项目和图像以及它们之间的关系

 class Item < ActiveRecord::Base
  attr_accessible :category_id, :user_id, :title, :description, :published, :start_date, :end_date, :images_attributes
  has_many  :images, :dependent => :destroy
  accepts_nested_attributes_for :images, :reject_if => :all_blank, :allow_destroy => true
  mount_uploader :name, ImageUploader 
end

class Image < ActiveRecord::Base
  belongs_to :item
  mount_uploader :image, ImageUploader  
  attr_accessible :item_id, :name  
end

我在items_controller.rb中调用Carrierwave的3个实例,将3个图像添加到创建的项目

def new
    @item = Item.new
    3.times { @item.images.build }
  end

视图表单如下所示:

<%= f.fields_for :images  do |builder| %>
   <p> <%= builder.text_field :name  %> </p>
 <% end %>

在这个已编译的代码中重新调整:  <input id="item_images_attributes_0_name" name="item[images_attributes][0][name]" type="file">

在我的数据库中添加并保存新项目保存对象数据而不是文件名(suit.jpg)时:

--- !ruby/object:ActionDispatch::Http::UploadedFile 
content_type: image/jpeg
headers: |
  Content-Disposition: form-data; name="item[images_attributes][0][name]"; filename="suit.jpg"
  Content-Type: image/jpeg

original_filename: suit.jpg
tempfile: !ru

从下面的数据库表中截屏:

https://lh3.googleusercontent.com/_USg4QWvHRS0/TXDT0Fn-NuI/AAAAAAAAHL8/91Qgyp5jK3Q/carrierwave-objest-database-saved.jpg

有谁知道如何解决它?

2 个答案:

答案 0 :(得分:1)

我有类似的问题,我想创建自己的文件名(标识符),所以我在上传器中定义了一个文件名方法(在你的情况下是ImageUploader) e.g。

def filename
  @name ||= "foo"
end

答案 1 :(得分:1)

首先,您将上传器安装到名为:image的列,但是从您的数据库的图片中,您没有带有所述名称的列。

1:为名为image的图片制作一个列(“那就是你的上传内容。”)

rails g migration add_image_to_images image:string
rake db:migrate

2:更新模型的attr_accessible以使用新列。

class Image < ActiveRecord::Base
  belongs_to :item
  mount_uploader :image, ImageUploader  
  attr_accessible :item_id, :name, :image  
end

3:更新你的观点

<%= f.fields_for :images  do |builder| %>
  <p> 
    <%= builder.text_field :name  %>
    <%= builder.file_field :image  %> 
  </p>      
<% end %>

4:从Item类中删除未使用的mount。

class Item < ActiveRecord::Base
  attr_accessible :category_id, :user_id, :title, :description, :published, :start_date, :end_date, :images_attributes
  has_many  :images, :dependent => :destroy
  accepts_nested_attributes_for :images, :reject_if => :all_blank, :allow_destroy => true
end

我离开了:在Image上使用了name作为可以添加到图像的任意值。

同样通过抽象你的图像模型,我也会假设你想跟踪图像顺序,所以也许一个额外的列也是一个好主意。

希望这会有所帮助。

相关问题