我對ROR很新,我正在構建一個ROR應用程序,每個產品都可以有很多圖像。 我使用paperclip
進行圖片上傳。在ROR應用程序中顯示來自數據庫的多個回形針圖像。很多關係
要做到這一點,我添加了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
所看到的代碼示例中的上述基於其類別I'm分組的產品,然後我展示每個類別有索引頁面上的任何產品。索引頁面上顯示的類別僅顯示每個類別中最新上傳的產品。
但現在在我有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
如果你的目標只是爲了顯示最新產品的圖像,然後你可以嘗試像'product = @ products.first'和然後'<%= image_tag product.images.first。 url(:medium),class:「img-responsive」%>' – Abhinay
感謝您的建議@Abhinay,但它給了我錯誤'未定義的本地變量或方法'產品'爲#<#:0x007fe0bc2d3a80> 你的意思是? product_url @ products' –
codegirl
@Abhinay我認爲@codegirl詢問如何在設置索引頁面的'loop'中設置同樣的功能,就像她在添加'image'模型之前一樣。但現在的區別是她將如何顯示每個類別中最新上傳產品的第一張圖片。 – DaudiHell