0

我有一个名为列表的模型。在我的 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>

<%= f.label :image %>
<%= f.file_field :image %> <%= f.submit %> <% end %> <%else%> <%=link_to "Sign in", new_user_session_path %>
联系管理员获取登录名和密码<%end%>

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

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

在此先感谢您的帮助。

4

2 回答 2

1

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

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

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

于 2012-05-26T03:56:45.017 回答
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 %>
于 2012-05-26T08:36:32.737 回答