简体   繁体   English

如何在文件系统Ruby on Rails中存储图像

[英]how to store image in file system Ruby on Rails

Two models. 两种模式。

Assets - used to upload files with paperclip. 资产-用于通过回形针上传文件。

class AddAttachmentsPhotoToAsset < ActiveRecord::Migration
  def self.up
    add_column :assets, :photo_file_name, :string
    add_column :assets, :photo_content_type, :string
    add_column :assets, :photo_file_size, :integer
    add_column :assets, :photo_updated_at, :datetime
  end

Boards - a blog 董事会-博客

class CreateBoards < ActiveRecord::Migration
  def self.up
    create_table :boards, :options => "AUTO_INCREMENT = 1000" do |t|
        t.column :deliver_on,    :datetime
        t.column :time_zone,     :string
      t.column :header_text,   :text
      t.column :name,          :string
      t.column :age,           :int, :default => "0"
      t.column :template_id,   :int, :default => "1", :null => false
      t.column :photo, :string
      t.timestamps
    end
  end

new.html.erb new.html.erb

There is an ajax iframe work around at the bottom of this form. 此表单底部有一个ajax iframe解决方案。 The user can upload a picture and view it on the form before submitting it. 用户可以上传图片并在提交之前在表单上查看。 Therefore there is no board that can be saved to upload the picture with. 因此,没有可以保存的板来上传图片。 So I had to create the asset object. 因此,我必须创建资产对象。

<% form_tag(action, :id => "form")  do %>
<%=image_tag board_image, :width => 140, :height => 166, :id => 'user_image' %><%= hidden_field :board, :photo, :id => 'image_name'%>

<%= error_messages_for :user,:board,  :header_message => "" %>
<%= label_tag  :name, "Friend's Name:", :class => "large"%>
<%= text_field :board, "name", :class => "large", :style => Board::NAME_WIDTH %>    
.
.
.
<%=submit_tag "#{button_text}", :id => "board_submit"%> 
<% end %>

This has to be outside of the other form or it won't work so I have it here at the bottom after the <% end %> tag of the other form. 这必须在另一种形式之外,否则将无法正常工作,因此我在另一种形式的<%end%>标记之后的底部将其放在此处。

iframe ajax style file upload of a picture. 图片的iframe ajax样式文件上传。

<% remote_form_for(:asset, :url => { :controller => "asset", :action => "upload", :id => @tmp_id }, :html => { :method => :post, :id => 'uploadForm', :multipart => true }) do |f| %>
<%= f.file_field :photo, :class => 'file' %>
<% end %>

upload.js upload.js

//ajax file upload
        $(function() { 
        $("#uploadForm input").change(function(){
         $("#uploadForm").ajaxSubmit({
          beforeSubmit: function(a,f,o) {
           o.dataType = "json";
          },
          complete: function(XMLHttpRequest, textStatus) {
          $('#user_image').attr('src', XMLHttpRequest.responseText +'?'+ new Date().getTime());
          $('#image_name').attr('value', XMLHttpRequest.responseText);
           return; false;
          },
         });
        });
        });

In assets_controller.rb 在assets_controller.rb中

 def upload
      if params_posted?(:asset) #check that the form was submitted with a post action
        @asset = Asset.new(params[:asset]) #create  new paperclip object to upload item
        @asset.save   #upload the photo
        render :text => @asset.photo.url #put the name on the form.
      end 
  end

In board_controller 在board_controller中

def create
...
@board.new(params[:board])
...


end

File gets uploaded with assets object. 文件与资产对象一起上传。 File is stored in assets table in database photo url is stored in the hidden field on the form. 文件存储在资产表中,数据库照片url存储在表单上的隐藏字段中。 Board is created and photo url is stored in the Boards table. 创建木板,并将照片URL存储在“木板”表中。

Thus I have stored photo data in two tables which does not seem correct. 因此,我将照片数据存储在两个看起来不正确的表中。

I am a newbie, green as there ever was. 我是一个新手,像往常一样绿色。

Is it better to store the asset.id of the Asset instance used to upload the images instead of the image url into the Board table? 将用于上传图像的Asset实例的asset.id而不是图像url存储到Board表中,是否更好?

To be clearer: 要更清楚:

Should I have a field in my Boards table 我应该在“ Boards”表中有一个字段吗

t.column asset_id

and then access the assets photo data someway? 然后以某种方式访问​​资产照片数据?

Thanks immensley in advance for your expertise. 预先感谢immensley的专业知识。

Actually, why not just connect the attachments to your board model instead of having two separate models for them? 实际上,为什么不将附件仅连接到您的电路板模型,而不是为它们配备两个单独的模型? are you using the assets for your other models? 您是否将资产用于其他模型? If not, it is better to just put the has_attachment in your board.rb model 如果不是,最好将has_attachment放在board.rb模型中

I found the answer here 我在这里找到答案

When I transfer the information from the @asset object to the board object. 当我将信息从@asset对象传输到board对象时。

In Board.rb I do as corroded suggested and add the paperclip item 在Board.rb中,按照建议的方式进行操作并添加回形针项目

 has_attached_file :photo  #I can also add styles, where I want to save the photo etc

So I don't think I need the boards photo from params. 因此,我认为我不需要params的木板照片。 I create it from the url of the @asset.photo.url. 我从@ asset.photo.url的URL创建它。

   @board.photo = @asset.photo

When I do @board.save it will trigger all of the paperclip methods as if the file was being uploaded because they get triggered when the items are saved. 当我执行@ board.save时,它将触发所有回形针方法,就好像文件正在上载一样,因为在保存项目时会触发它们。 So they will be copied from the temp location to where I want them to reside when I have a board. 因此,将它们从临时位置复制到当我有板子时我希望它们驻留的位置。 I then have to delete out the temp directories and the assest in the assets table as its done its job. 然后,在完成工作时,我必须删除temp目录和资产表中的资产。

Update: It is all working perfectly now. 更新:现在一切正常。 I have corrected the code above. 我已更正上面的代码。

important note!!!!! 重要的提示!!!!!

you must do the following after you save the new model or the url and path values will be wrong. 保存新模型后,必须执行以下操作,否则url和path值将错误。

model.photo.reprocess! model.photo.reprocess!

(replace model with your model.In my case it was @board.photo.reprocess!) (用您的模型替换模型。在我的情况下是@ board.photo.reprocess!)

That is my final answer 那是我的最终答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM