两种模式。如何在文件系统中存储图像Ruby on Rails
资产 - 用于使用回形针上传文件。
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
板 - 一个博客
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
有一个Ajax的iframe工作围绕在这种形式的底部。用户可以上传图片并在提交之前在表格上查看图片。因此没有可以保存的板子来上传图片。所以我必须创建资产对象。
<% 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 %>
这有可能是其他形式之外,否则将无法工作,所以我把它在这里的其他形式的<%结束%>标记之后的底部。
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
//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;
},
});
});
});
在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
在board_controller
def create
...
@board.new(params[:board])
...
end
文件获取与资产Ø上传bject。 文件存储在资产表中的数据库 照片URL存储在窗体的隐藏字段。 电路板已创建,照片URL存储在电路板表中。
因此,我已经将照片数据存储在两张表中,看起来不正确。
我是一个新手,一如既往的绿色。
将Asset实例的asset.id用于上传图片而不是图片url到Board表中更好吗?
更清晰:
我应该有一个外地在我的主板表
t.column asset_id
,然后好歹访问资产照片数据?
非常感谢immensley为您提供的专业知识。
由于腐蚀。我想这样做。问题是我在表单被保存之前上传照片,以便用户可以在表单上看到图像。我无法使用板对象来保存它们,因为这需要我保存板来上传图像。董事会不会保存,因为它缺少所需的数据,如姓名或电子邮件地址。就我所见,还是我错了? – chell 2011-03-23 10:58:54
该关联将为:董事会belongs_to:资产资产has_one:董事会。这听起来很奇怪。这就是为什么我不认为它是正确的。我如何在理事会和资产之间建立一种有意义的联系。 – chell 2011-03-23 17:07:48
董事会has_one:资产和资产belongs_to:董事会。那更符合逻辑吧?因为它是具有资产 – corroded 2011-03-23 17:50:26