Rails提取图像附件

时间:2015-12-29 04:24:39

标签: ruby-on-rails ruby

在我的rails应用中,我需要获取与产品相关联的第一个图像附件。以下是我的代码:

backgroundcolor

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

如何仅获取与产品相关联的一个图像?

1 个答案:

答案 0 :(得分:1)

这个怎么样: html <img class="img-responsive" src="<%= product.product_attachments.first %>" width="262" alt="">