1

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?

michaeldever
  • 359
  • 4
  • 14
Aaquib Khan
  • 83
  • 1
  • 9

1 Answers1

1

Try with includes to get rid of [N+1] queries:

category = Category.includes(:products).find_by(type: 'Laptop')

products = category.products
Sebastián Palma
  • 32,692
  • 6
  • 40
  • 59
Ranjan
  • 96
  • 2
  • 9
  • thank you,but i think my categories are not getting saved in my products and can you plz check my edited question and guide me through it. – Aaquib Khan Aug 12 '17 at 17:49
  • issue solved but why iam getting value" true"on my screen when iam displaying the products ? – Aaquib Khan Aug 12 '17 at 18:14