[英]Uploading image with paperclip+rails. How to save the image to a different model than the uploading model
我有一个名为Listing的模型。 在我的index.html.erb中列出。 我在屏幕上显示了所有列表。 Listing模型的_form.html.erb如下所示:
<%if user_signed_in? %>
<%=link_to "Sign Out", destroy_user_session_path, :method => :delete %><br/>
<%= form_for(@listing, :html => {:multipart => true} ) do |f| %>
<% if @listing.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@listing.errors.count, "error") %> prohibited this listing from being saved:</h2>
<ul>
<% @listing.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :id %><br />
<%= f.text_field :id %>
</div>
<%= f.label:image%>
<%= f.file_field:image%> <%= f.submit%> <%end%> <%else%> <%= link_to“登录”,new_user_session_path%>
联系管理员以获取登录名和密码<%end%>
这里与该视图相关联的模型是“列表”,但我想将上传的图像属性存储在应用程序中的不同模型中:“图像”。
基本上我想做的是,让我的所有模特通过他们的视图上传他们自己的照片,但是将所有图像属性保存在一个名为“Image”的模型中。 图像本身存储在Amazon S3上。
所以问题是“清单”模型中的代码是如何实现的,以及“图像”模型中的代码是如何实现的。 这些信息如何从列表传递到图像?
目前在Listing模型中:
class Listing < ActiveRecord::Base
has_attached_file :image,:styles => {:thumb => "75x75>", :small => "150x150>", :medium => "300x300>"}
end
目前处于“图像”模型
# == Schema Information
#
# Table name: images
#
# id :integer not null, primary key
# image_file_name :string(255)
# image_content_type :string(255)
# image_file_size :integer
# image_type :string(255)
# created_at :datetime not null
# updated_at :datetime not null
#
class Image < ActiveRecord::Base
end
在此先感谢您的帮助。
我假设列表和图像之间存在关系,但你明白了
<% fields_for @listing.image do | img | %>
<%= img.file_field :image %>
#etc
<% end %>
<% end %>
当然,如果您不希望它们相关,您可以创建一个新的Image对象并将其传递给field_for,但保持它们相关是有意义的!
只是为了明确,这是你的模型中你会有的:
上市模型
class Listing < ActiveRecord::Base
has_one :image, dependent => :destroy
end
图像模型
class Image < ActiveRecord::Base
has_attached_file :image,
:styles => {:thumb => "75x75>",
:small => "150x150>",
:medium => "300x300>"}
end
然后在你的表格(来自DVG的答案):
<% fields_for @listing.image do | img | %>
<%= img.file_field :image %>
#etc
<% end %>
<% end %>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.