Reputation: 2586
In my rails app, I need to fetch the first image attachment associated with product. Following were my code:
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
model:
class ProductAttachment < ActiveRecord::Base
mount_uploader :attachment, AttachmentUploader
belongs_to :product
end
Product
model:
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
This is my view:
<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>
How can I fetch only one image associated with the product?
Upvotes: 1
Views: 108
Reputation: 2878
How about this:
html
<img class="img-responsive" src="<%= product.product_attachments.first %>" width="262" alt="">
Upvotes: 1