I am modifying the Rails application I have been working on.
I installed a model images.rbfor processing all images for products.
When a user selects a product, the user sees the product in app/views/products/show.html.erb
And at the bottom, the show.html.erbapplication gives suggestions for the user for a similar product in the same category as the product that the user is looking at.
Before I added a model image.rbfor image processing, each product had one image attached to it, and everything worked, but now I get an error message. Below is the code that I used to display random products in the same category:
the show.html.erb
<div class="row product-teaser">
<h4 class="text-center teaser-text"> similar products to <%= @product.title %> : </h4>
<% @products_rand.each do |product| %>
<div class="col-sm-2 col-xs-3 center-block product-thumbs-product-view" >
<%= link_to product_path (product) do %>
<%= image_tag @product.image.url, :size => "100%x100%", class: "img-responsive center-block" %>
<% end %>
<h5 class="text-center"><%= link_to product.title, product, class: "text-center" %></h5>
</div>
<% end %>
</div>
products_controller.rb show .
class ProductsController < ApplicationController
before_action :set_product, only: [:show, :edit, :update, :destroy]
def show
@products_rand = Product.where(category_id: @product.category_id).order("RANDOM()").limit(6)
end
private
def set_product
@product = Product.find(params[:id])
end
def product_params
params.require(:product).permit(:title, :description, :price_usd, :image, :category_id, :stock_quantity, :label_id, :query, :slug, images_attributes: [:image , :id , :_destroy])
end
end
image.rb : undefined method 'url' for "":String . : <%= image_tag @product.image.url, :size => "100%x100%", class: "img-responsive center-block" %>
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
validates :title, :description, presence: true
validates :price_usd, :price_isl, numericality: {greater_than_or_equal_to: 0.01}
validates :title, uniqueness: true
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
, , - ?