Reputation: 1735
I have created a controller and a model for my application. I want to get the data in json format. Where can I see my output? If I run the controller it doesn't respond. I am listing the files. Finally I want to get data from the products
table from database in json format. What to do to get my data?
My Controller:
class ShoppingDemo < ApplicationController
def index
@lists=Product.all;
respond_to do |format|
format.html
format.json { render json: @lists}
end
end
def show
@products = products.find(params[:prod_id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @products }
end
end
end
My Model:
class product < Activerecord::Base
attr_accessible :model_name, :brand_name, :price, :discount, :qty_available
end
show.html.erb
<p>
<b>model_name:</b>
<%= @products.model_name %>
</p>
<p>
<b>Brand_name:</b>
<%= @products.brand_name %>
</p>
<p>
<b>Price:</b>
<%= @products.price %>
</p>
<p>
<b>Discount:</b>
<%= @products.discount %>
</p>
<p>
<b>Quantity:</b>
<%= @products.qty_available %>
</p>
Upvotes: 0
Views: 92
Reputation: 1305
Write the following inside products_controller.rb file.
def index
@products = Product.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: @products }
end
end
def show
@product = Product.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @product }
end
end
In your routes.rb file add the following line.
resources :products
And go ahead accordingly.
I could find you are not much aware of ruby on rails. Please have a look on the document.
http://guides.rubyonrails.org/
Upvotes: 0
Reputation: 1305
First of all, your query in show method is completely wrong.
Write show method like following:
def show
@products = Product.find(params[:prod_id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @products }
end
end
And write <%= @products.to_json %>
in your show.html.erb.
Otherwise you can check by adding the .json
extension in the url. Eg: http://localhost:3000/shopping_demos/1.json
Upvotes: 1