【问题标题】:Uploading image with paperclip+rails. How to save the image to a different model than the uploading model使用回形针+导轨上传图像。如何将图像保存到与上传模型不同的模型
【发布时间】:2012-05-26 22:30:28
【问题描述】:

我有一个名为列表的模型。在我的 index.html.erb 中进行列表。我有屏幕上的所有列表。清单模型的 _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>



联系管理员获取登录名和密码

这里与此视图关联的模型是“Listing”,但我想将上传的图像属性存储在应用程序中的不同模型中:“Image”。

基本上我想做的是,让我所有的模型通过他们的视图上传他们自己的照片,但将所有图像属性保存在一个名为“图像”的模型中。图像本身存储在 Amazon S3 上。

所以问题是“列表”模型中的哪些代码可以实现这一点,以及“图像”模型中的哪些代码可以实现这一点。以及这些信息是如何从 Listing 传递到 Image 的?

目前在列表模式中:

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

提前感谢您的帮助。

【问题讨论】:

    标签: ruby-on-rails ruby file-upload paperclip


    【解决方案1】:

    为了明确起见,以下是您的模型中的内容:

    上市模式

    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 %>
    

    【讨论】:

      【解决方案2】:

      我假设列表和图像之间存在关系,但你明白了

      <% fields_for @listing.image do | img | %>
        <%= img.file_field :image %>
        #etc
        <% end %>
      <% end %>
      

      当然,如果您不希望它们相关,您可以创建一个新的 Image 对象并将其传递给 field_for,但保持它们相关是有意义的!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-03-31
        • 2017-08-26
        • 1970-01-01
        • 1970-01-01
        • 2022-01-11
        • 2016-11-09
        • 1970-01-01
        • 2014-10-16
        相关资源
        最近更新 更多