How to get json response in rails api - ruby

I want to display all programmes which I got from a query as json response. I'm getting the programmes, but don't know how to render them through json. I'm using the jbuilder gem and created a create.json.buider.rb file. In my query I'm getting everything correctly, but I'm not receiving a JSON response with whatever details in I have in the query.
This is my controller. I have tried it like this but I'm not getting a json response. Only a status as 200.
class Api::V1::Categories::ProgrammesController < ApiController
respond_to :json
def category
#category=Category.all
#programmes=Programme.joins(:category).find_by(category_id: params[:category_id])
if #programmes.present?
render :json=> {:message=>"Programme not exists "}, :status=>422
else
render :json => #programmes
end
end
end
My create.json.jbuilder file:
json.programmes #programmes

I think you should change #programmes to { :programmers => #programmes.as_json }
class Api::V1::Categories::ProgrammesController < ApiController
def category
#category = Category.all
#programmes = Programme.joins(:category).find_by(category_id: params[:category_id])
if #programmes.present?
render :json=> {:message=>"Programme not exists "}, :status=>422
else
render :json => { :programmers => #programmes.as_json }
end
end
end

Related

ActiveModel serializer ignores root key when posts or post is empty or nil

I am using active model serializer V0.10.0 with Rails 5 api only application. During implementation I noticed the AMS is completely ignoring the root key when the posts/post is empty or nil respectively. This behavior actually breaks my mobile app as it always expects root key data in all response.
So what I want to achieve here is no matter what I always want data as root element of my Rails app response for all requests.
Response for SHOW API when the post is empty
SHOW render json: #post, root: 'data'
Expected
{
"data": {}
}
Actual
null
Response for INDEX API when the posts are empty
INDEX render json: #posts, root: 'data'
Expected
{
"data": []
}
Actual
{
"posts": []
}
class ApplicationSerializer < ActiveModel::Serializer
include Rails.application.routes.url_helpers
ActiveModelSerializers.config.adapter = :json
def host
Rails.application.secrets.dig(:host_url)
end
end
class PostSerializer < ApplicationSerializer
attributes :id
has_many :comments
end

Testing with Postman keeps returning Invalid JSON error

I have created REST Api in Ruby on Sinatra platform. I am testing the service with Postman and whatever JSON form I try to POST I keep getting an error 400 Invalid JSON SUCKER. The error is defined on the back end in case of invalid JSON form. Please take a look at the back end and tell me what am I doing wrong.
I have to mention that GET method works with Postman and cURL from the command line while POST works only if I use it with cURL but NOT in POSTMAN.
#server.rb
require 'sinatra'
require 'mongoid'
require 'sinatra/namespace'
require 'sinatra/base'
#require 'json'
before do
content_type :json
headers 'Access-Control-Allow-Origin' => '*',
'Access-Control-Allow-Methods' => ['OPTIONS', 'GET', 'POST', 'PATCH']
end
#load database config
Mongoid.load! "mongoid.config"
#Class Company
class Company
include Mongoid::Document
field :compid, type: String
field :name, type: String
field :address, type: String
field :city, type: String
# validates :compid, presence: true
# validates :name, presence: true
index({ compid:1 }, { unique: true, name: "compid_index" })
index({ name: 'text' })
scope :name, -> (name) { where(name: /^#{name}/) } # this could be changed to /^#{title}/i to make case insensitive searcg =end
scope :compid, -> (compid) { where(compid: compid) }
end
#Serializers
class Serializer
def initialize(company)
#company = company
end
def as_json(*)
data ={
id:#company.compid.to_s,
name:#company.name,
address:#company.address,
city:#company.city,
}
data[:errors] = #company.errors if#company.errors.any?
data
end
end
# Endpoints
get '/' do
'List of all Companies'
end
namespace '/api/v1' do
before do
content_type 'application/json'
end
helpers do
def base_url
#base_url ||= "#{request.env['rack.url_scheme']}://{request.env['HTTP_HOST']}"
end
def json_params
begin
JSON.parse(request.body.read)
rescue
halt 400, { message:'Invalid JSON' }.to_json
end
end
end
get '/companies' do
companies = Company.all
[ :name, :compid,].each do |filter|
companies = companies.send(filter, params[filter]) if params[filter]
end
#put it through the serializer not to get all te atributes
companies.map { |company| Serializer.new(company) }.to_json
end
get '/companies/:compid' do |compid| #get the details about the company by searching with compid
company = Company.where(compid: compid).first
halt(404, { message:'Company Not Found'}.to_json) unless company
Serializer.new(company).to_json
end
post '/companies' do
company = Company.new(json_params)
if company.save
response.headers['Location'] = "#{base_url}/api/v1/companies{company.copmid}" # "{company.id}"
status 201
else
status 422
body Serializer.new(company).to_json
end
end
The data that I GET with the Postman looks like this:
[{"id":"5a1271f7943e8a0f5fd76008","name":"The Power Of Habit","address":"Charles Duhigg Vej","city":"Viborg"}]
I have tried to POST data in various forms:
[{"id":"5a1271f79asdd76008","name":"The Power Of Habit","address":"Charles Duhigg Vej","city":"Viborg"}]
{"id":"5a1271f79asdd76008","name":"The Power Of Habit","address":"Charles Duhigg Vej","city":"Viborg"}
[{"compid":"5a1271f79asdd76008","name":"The Power Of Habit","address":"Charles Duhigg Vej","city":"Viborg"}]
{"compid":"5a1271f79asdd76008","name":"The Power Of Habit","address":"Charles Duhigg Vej","city":"Viborg"}

Passing post data to other pages in Sinatra

This seems to work fine:
views/index.haml:
%form{:method => 'POST' :action => '/'}
%label{:for => 'name'} Name:
%input{:type => 'text, :value => #values[:name] || ""}
%input{:type => 'submit'}
app.rb:
post '/' do
#values = params
haml :review
end
views/review.rb
Hello #{params[:name]}!
However, when I try to send my post-data to the same view on a different URL I get an error, or in other words:
app.rb:
post '/' do
#values = params
redirect '/review'
end
get '/review' do
#values = params
haml :review
end
The data is not going through, but no error is raised.
How do I send the post-data across pages like this? Ideally, I do not want to create a database.
You can store the parameters in a session or specify the query string explicitly. Browser Redirect from Sinatra Documentation
As specified in the documentation, you may use sessions or convert the POST params to a query string and use it in the redirect method. A crude example would be:
Say the POST params hash inside the '/' block is:
{
:name => "Whatever",
:address => "Wherever"
}
This hash can be made into a string like so:
query = params.map{|key, value| "#{key}=#{value}"}.join("&")
# The "query" string now is: "name=Whatever&address=Wherever"
Now use this inside the post '/' do
redirect to("/review?#{query}")

how to use sunspot_mongo

In my application i have created a model under mongoDB, then i reindexed it to solr using sunspot_mongo. I want to search from solr,
My model is,
`require 'sunspot_mongo'
class Post
include Mongoid::Document
include Sunspot::Mongo
field :title
field :content
field :author, type: String
searchable do
text :title, :stored => true
text :content
end
end`
and my controller index method is,
def index
##posts = Post.all
search=Post.search do
fulltext 'hello'
end
#posts = search.results
respond_to do |format|
format.html # index.html.erb
format.json { render json: #posts }
end
end
but it showing error as,
uninitialized constant Sunspot::Mongo::DataAccessor::BSON
i couldn't fix this error
i used this in gem file
gem "sunspot_mongo", :git => "git://github.com/balexand/sunspot_mongo.git", :branch => "fix_rake_sunspot_reindex"
your model looks fine
change your controller code as below
def index
search=Post.solr_search do
fulltext params[:search]
end
#posts = search.results
respond_to do |format|
format.html # index.html.erb
format.json { render json: #posts }
end
end

Mongoid _destroy is not deleted embedded document using nested_form gem

I am on Rails 3.1, Mongoid 2.3.3, and using the nested_form gem. In my form, I have the nested_form link_to_add and link_to_remove set up to add and remove an embedded document in my model. The link_to_add helper method works great, but the link_to_remove help method changes are not persisted in MongoDB. In the rails output, I can see the JSON parameter passed to Mongoid has the _destroy: 1 value set but the change is not saved to MongoDB.
Here is the Model:
class MenuItem
include Mongoid::Document
include Mongoid::Timestamps
field :name
attr_accessible :name
embeds_many :ingredient_infos
accepts_nested_attributes_for :ingredient_infos, :allow_destory => true
attr_accessible :ingredient_infos_attributes
end
Here is the Controller's update method:
def update
#menu_item = MenuItem.find(params[:id])
respond_to do |format|
if #menu_item.update_attributes(params[:menu_item])
format.html { redirect_to #menu_item, notice: 'Menu item was successfully updated.' }
format.json { head :ok }
else
format.html { render action: "edit" }
format.json { render json: #menu_item.errors, status: :unprocessable_entity }
end
end
end
Here is the parameters sent to the controller:
{
"utf8"=>"✓",
"authenticity_token"=>"5abAWfFCr7hkzYXBEss75qlq8DMQ0pW5ltGmrgHwPjQ=",
"menu_item"=>
{
"name"=>"Bowl",
"ingredient_infos_attributes"=>
{
"0"=>
{
"ingredient"=>"Rice",
"_destroy"=>"false",
"id"=>"4eb1b0b118d72f1a26000022"
},
"1"=>
{
"ingredient"=>"Chicken",
"_destroy"=>"1",
"id"=>"4eb1b0b118d72f1a26000025"
}
}
},
"commit"=>"Update Menu item",
"id"=>"4eb1b0b118d72f1a2600001f"
}
In MongoDB, the Chicken document still exists; that document also shows up in the view online (the page pulls all the items in the embedded document).
I'm sure I missed something, but I haven't been able to figure out why the embedded document isn't removed.
yes, your :allow_destory should be :allow_destroy
I am experiencing the same issue -
RESOLVED with
accepts_nested_attributes_for :phones, :allow_destroy => true

Resources