I am having trouble debugging this error. NoMethodError in Products#Index undefined method 'id' for #ActiveRecord::Relation
Here is my products controller:
class ProductsController < ApplicationController
def index
if params[:query].present?
@products = Product.search_by_name_and_category(params[:query])
else
@products = Product.all
end
end
def new
@product = Product.new
@product.user = current_user
end
def show
@product = Product.find(params[:id])
end
end
Here is my product model:
class Product < ApplicationRecord
belongs_to :user
has_many :bookings
validates :name, presence: true
validates :category, presence: true
has_one_attached :photo
include PgSearch::Model
pg_search_scope :search_by_name_and_category,
against: [ :name, :category ],
using: {
tsearch: { prefix: true } # <-- now `superman batm` will return something!
}
end
This is my product-card partial.
<div class="card-product-container">
<div class="cards">
<div class="card-product">
<%= link_to product_path(@products.id) do %>
<img src="https://source.unsplash.com/random/?<%= product.name %>" />
<div class="card-product-footer">
<div>
<h2><%= product.name %></h2>
<p><%= product.category %></p>
</div>
<h2><%= product.price %></h2>
</div>
<% end %>
</div>
</div>
@products is a list of many Products. The list doesn't have an ID. Each Product in the list does.
You instead want the ID of a each individual Product in @products.
Iterate through @products and work with a single Product.
<% @products.each do |product| %>
<div class="card-product">
<%= link_to product_path(product.id) do %>
<img src="https://source.unsplash.com/random/?<%= product.name %>" />
<% end %>
<div class="card-product-footer">
<div>
<h2><%= product.name %></h2>
<p><%= product.category %></p>
</div>
<h2><%= product.price %></h2>
</div>
</div>
<% end %>