2015-12-29 30 views
1

在我的Rails应用程序中,我需要获取与产品关联的第一个图像附件。下面是我的代码:Rails提取图像附件

class HomeController < ApplicationController 
    skip_before_action :authenticate_user! 

    def index 
     @products = Product.first 
     @product_attachments = ProductAttachment.first 
     logger.info "status=Fetching Home Product image=#{@products.product_attachments.attachment.url}" 
    end 


end 

ProductAttachment型号:

class ProductAttachment < ActiveRecord::Base 

    mount_uploader :attachment, AttachmentUploader 
    belongs_to :product 
end 

Product型号:

class Product < ActiveRecord::Base 


    belongs_to :user 
    belongs_to :product_category 
    belongs_to :location 
    has_many :product_attachments, dependent: :destroy 
    accepts_nested_attributes_for :product_attachments, allow_destroy: true 
    has_many :variants, dependent: :destroy 
    accepts_nested_attributes_for :variants, reject_if: proc { |attributes| attributes['name'].blank? } 


    attr_accessor :product_overview_url 
    attr_accessor :user_avatar_url 

    validates :name, :presence => true 
    validates :product_category_id, :presence => true 
    validates :payment_type, :presence => true 

end 

这是我的看法:

<div class="row"> 
      <div class="col-md-12 text-center content-title"> 
       <h3>New York</h3> 
      </div> 
      <% @products.each do |product| %> 
      <div class="col-md-3 portfolio-item"> 
       <p class="price">USD <%= product.price_cents/100 %></p> 
       <a href="#"><img src="https://s3.amazonaws.com/uifaces/faces/twitter/nuraika/128.jpg" class="img-circle user-thumb" width="52"/></a> 
       <a href="#"> 
       <img class="img-responsive" src="<%= product.product_attachments%>" width="262" alt=""> 
       </a> 
       <h4> 
        <a href="#"><%= product.name %></a> 
       </h4> 
       <a href="#"> 
        <p><%= product.city%>, <%= product.country%></p> 
       </a> 
      </div> 
      <% end %> 

     </div> 

我如何获取只有一个图像关联与产品编辑?

+1

那么,为什么不试试'product.product_attachments.try(:第一)'? –

回答

1

如何: html <img class="img-responsive" src="<%= product.product_attachments.first %>" width="262" alt="">