I am building a e-commerce app and i have a product model and a category model.as below
class Product
belongs_to :category
end
Category model:
class Category
has_many :products
end
In my views, while creating Products I have a select box from which I choose a category. My problem is that I have to display products according to categories e.g. "Laptop","Mobile" etc. As joins dont work in mongoid what should I do to display products based on category for example on laptop category I have to show all products with category Laptops. Please help me I am new to Rails and mongoid especially.
EDIT:
I think the categories are not getting saved in my products via select box.
My create method:
class ProductsController < ApplicationController
def create
@product = current_user.products.build(product_params)
@categories = Category.all
respond_to do |format|
if @product.save
format.html { redirect_to @product, notice: 'Product was successfully created.' }
format.json { render :show, status: :created, location: @product }
else
format.html { render :new }
format.json { render json: @product.errors, status: :unprocessable_entity }
end
end
end
def product_params
params.require(:product).permit(:user_id, :name, :description,:avatar,:prize,:category_id)
end
end
my view for products
<%= form_for @product, :html => {:multipart => true} do |f| %>
<div class="field">
<%= f.label :name %><br>
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :prize %><br>
<%= f.text_field :prize %>
</div>
<div class="field">
<%= f.label :Select_Category %><br>
<%= f.select :category_id, @categories.map{ |c| [c.name, c.id] } %>
</div>
<div class="field">
<%= f.label :avatar %><br>
<%= f.file_field :avatar %>
</div>
<div class="field">
<%= f.label :description %><br>
<%= f.text_area :description %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
What should I add in controller to get categories saved in products?