我对 ROR 很陌生,我正在构建一个 ROR 应用程序,每个产品都可以有很多图像。 我使用paperclip
上传图像。
为此,我向应用程序添加了一个image.rb
模型,现在product.rb
模型has_many :images
并accepts_nested_attributes_for :images
。
这一切都很好,没有问题。
问题是product.rb
模型具有这种belongs_to :category
和belongs_to :label
的关系
和category
和label
都has_many :products
在我添加image.rb
模型之前,每个产品都附有一张图片。 在index.html.erb
页面,用户可以看到类别排列,类别中每个产品的最新上传图片作为每个类别的正面图片。
下面是我在添加image.rb
模型之前用于在index.html.erb
显示类别的截图。
<div class="container-fluid">
<% @products.each_slice(3) do |products_group| %>
<div class="row">
<% products_group.each do |category, products| %>
<% products.each_with_index do |product, index| %>
<% if index == 0 %>
<div class="col-lg-4 col-sm-6 col-xs-12 center-block " >
<%= link_to category_path (category), { :method => 'GET' } do %>
<%= image_tag product.image.url(:medium), class: "img-responsive" %>
<% end %>
<div class="caption">
<p class="category-name" ><%= product.category.name %></p>
</div>
<% end %>
<% end %>
</div>
<% end %>
</div>
<% end %>
</div>
在pages_controller.rb
中有这样的代码:
def index
@products = Product.all.order(created_at: :desc).group_by(&:category_id)
end
如上面的代码示例所示,我根据类别对产品进行分组,然后在索引页上显示具有任何产品的每个类别。索引页面上显示的类别仅显示每个类别中最新上传的产品。
但是现在,在我有了image.rb
模型来处理照片上传之后,我需要一种方法在索引页面上显示相同的结果,但是当用户点击某个类别时,他会被带到该类别页面。
这是一个问题,因为现在图像绑定到image.rb
模型,但不再是product.rb
模型。
我可以在image.rb
模型中看到上传的图片,但我不确定我应该如何在不破坏所有内容的情况下调整关系。
有人可以帮我吗?
以下是涉及的模型:
product.rb
class Product < ActiveRecord::Base
acts_as_list :scope => [:category, :label]
belongs_to :category
belongs_to :label
has_many :images
accepts_nested_attributes_for :images
has_many :product_items, :dependent => :destroy
end
category.rb
class Category < ActiveRecord::Base
has_many :products, :dependent => :nullify
extend FriendlyId
friendly_id :name, use: [:slugged, :finders]
end
和image.rb
class Image < ActiveRecord::Base
belongs_to :product
has_attached_file :image, styles: { medium: "500x500#", thumb: "100x100#" }
validates_attachment_content_type :image, content_type: /Aimage/.*z/
end
在每个产品中都有一个图像之前。现在,产品中有许多图像。我认为您只需要在image_tag之前进行迭代:
以前:
<%= image_tag product.image.url(:medium), class: "img-responsive" %>
后:
<% product.images.each do |image_model| %>
<%= image_tag image_model.image.url(:medium), class: "img-responsive" %>
<% end %>
如果要显示第一张图片:
<% if product.images.first %>
<%= image_tag product.images.first.image.url(:medium), class: "img-responsive" %>
<% end %>