Hi I am trying to set up categories on my e-commerce website using Ruby on Rails, what I want to do is have pages which shows products from a specific category for example I have the category t-shirt so all t-shirts are shown etc… In the backend I am able to set a products category, as I have assigned a foreign key category_id to the products table and the the relationship in the models for the category is it has many products and for the products model it belongs to a category. What would I have to do for showing products from a specific category?
Here is my current code:
Store controller
class StoreController < ApplicationController
skip_before_filter :authorize
def index
@cart = current_cart
@products = Product = Product.search(params[:search]).paginate(:page => params[:page], :per_page => 6)
end
end
Category controller
class CategoriesController < ApplicationController
# GET /categories
# GET /categories.json
def index
@categories = Category.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: @categories }
end
end
# GET /categories/1
# GET /categories/1.json
def show
@category = Category.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @category }
end
end
end
As far as I can tell, there’s no reason you can’t use the collections Rails provides when you specify a one-to-many association: