FInding error developing API in Rails - ruby-on-rails

I juts start with the developing of an API using RAILS. Im doing a simple example of my own but I have an error when I want to see the result in my API.
Controller:
class EnergyCalcController < ApplicationController
def index
file_path = Rails.root.join('db','test_file.js')
file_gen = File.read(file_path)
#data_hash_gen = JSON.parse(file_gen)
end
end
In controllers/api/energy_calc_controller.rb
class Api::EnergyCalcController < ApplicationController
def index
render json: #data_hash_gen
end
end
Routes
Rails.application.routes.draw do
namespace :api do
resources :energy_calc
end
get 'energy_calc/index'
Views/energy_calc/index.html.erb
<h1>EnergyCalc#index</h1>
<p>Find me in app/views/energy_calc/index.html.erb</p>
<%= #data_hash_gen %>
In the view is printing me the data normally. But when I tried to access: http://localhost:3000/api/energy_calc.json I got null
Any idea?

Put your EnergyCalcController index methods code in to Api::EnergyCalcController's index method. Like this,
class Api::EnergyCalcController < ApplicationController
def index
file_path = Rails.root.join('db','test_file.js')
file_gen = File.read(file_path)
#data_hash_gen = JSON.parse(file_gen)
render json: #data_hash_gen
end
end

You don't need to have two different controllers for rendering different formats.It is redundant.You could render HTML and JSON both in a single action.
class EnergyCalcController < ApplicationController
def index
file_path = Rails.root.join('db','test_file.js')
file_gen = File.read(file_path)
#data_hash_gen = JSON.parse(file_gen)
respond_to do |format|
format.json {
render :json => #data_hash_gen
}
format.html {
#Objects exclusively needed to render html
}
end
end
end

Related

How to json response according to search params

I want to get json response according to filters. Now on page load I'm getting json response for the every properties which are listed in that page.
In the same page I have filters, so if I search property through filters according to that json response should change.
class PropertiesController < ApplicationController
def index
if params[:city].present?
#properties=Property.where("properties.city = ? ",params[:city],"%#{params[:city]}%")
elsif params[:cityname].present?
#properties=Property.where("properties.city = ? ",params[:cityname])
else
#properties = Property.where("properties.status = ?", '1')
end
respond_to do |format|
format.html # index.html.erb
format.json { render json: #properties.as_json(only: [:id, :latitude, :longitude]) }
end
end
end
What is wrong with my code?

(RoR) json and nested objects: get attribute in object of object

My goal is an output like this (for each attachment):
url:
"/uploads/attachment/picture/15/5ee306c9-e263-466b-b56d-1c7c9d2ae17b.jpg"
What I have at the moment:
attachments_controller.rb
class AttachmentsController < ApplicationController
before_action :logged_in_user
def index
#attachments = current_user.attachments.all
respond_to do |format|
format.json do
render :json => #attachments.each{ |o| o.picture.url }
end
end
end
...
Try
respond_to do |format|
format.json do
render :json => #attachments.map { |o| { url: o.picture.url } }
end
end

"param is missing or the value is empty: color" error in controller

I followed a tutorial on YouTube involving making a simple model, printing out the results and updating the model with a form and did a find and replace for what I was trying to accomplish ("text files, the tutorial involved images)
Everything worked up until around the time I just wanted an single index page and tried merging all the controller logic into the index.
I'm currently getting an error reading param is missing or the value is empty: color on params.require in the controller below.
class ColorsController < ApplicationController
before_action :find_color, only: [:destroy]
def index
#colors = Color.all.order("created_at DESC")
#color = Color.new(color_params)
end
def destroy
#color.destroy
end
private
def find_color
#color = Color.find(params[:id])
end
def color_params
params.require(:color).permit(:file)
end
end
What I take from this is that it's not recognizing the #color instance variable, but I don't know or why I'm supposed to rectify this.
Model:
class Color < ActiveRecord::Base
has_attached_file :file
validates_attachment_content_type :file, :content_type => ["application/xml"]
end
Form:
= simple_form_for #color do |f|
= f.input :file
= f.submit
Explanation of what I'm doing wrong is much appreciated.
param is missing or the value is empty: color
You should change your index method to below
def index
#colors = Color.all.order("created_at DESC")
#color = Color.new #notice the change here
end
Also, you should define a create method like below
def create
#color = Color.new(color_params)
respond_to do |format|
if #color.save
format.html { redirect_to #color, notice: 'Color was successfully created.' }
format.json { render :show, status: :created, location: #color }
else
format.html { render :new }
format.json { render json: #color.errors, status: :unprocessable_entity }
end
end
end

How do I override Kaminari pagination when rendering JSON in the respond_to block?

I want to override Kaminari's pagination when rendering JSON, or tell it to return all with pagination.
In App1, I am using ActiveResource to access App2's Group model:
class Group < ActiveResource::Base
self.site = "http://www.app2.com:3000"
end
Here's App2's Group model:
class Group < ActiveRecord::Base
default_scope order('name asc')
paginates_per 10
This is my controller. The Group.search stuff is ransack:
class GroupsController < ApplicationController
# GET /groups
# GET /groups.json
def index
#search = Group.search(params[:q])
#groups = #search.result.page params[:page]
respond_to do |format|
format.html # index.html.erb
format.json { render json: #groups }
end
end
I've added eleven groups to App2. In the console of App1 I get:
[45] pry(main)> Group.all.count
=> 10
What is the best way to do this without changing the HTML pagination rendering?
You can prepare all the common logic you need but only apply pagination for the HTML format:
def index
#search = Group.search(params[:q])
#groups = #search.result
respond_to do |format|
format.html { #groups = #groups.page(params[:page]) }
format.json { render :json => #groups }
end
end
You can run different code in different formats:
def index
respond_to do |format|
format.html {
#search = Group.search(params[:q])
#groups = #search.result.page params[:page]
} # index.html.erb
format.json {
render json: Group.all
}
end
end

How do you render hashes as JSON in Rails 3

I found how to render ActiveRecord objects in Rails 3, however I cannot figure out how to render any custom objects. I am writing an app without ActiveRecord. I tried doing something like this:
class AppController < ApplicationController
respond_to :json
...
def start
app.start
format.json { render :json => {'ok'=>true} }
end
end
When you specify a respond_to, then in your actions you would make a matching respond_with:
class AppControlls < ApplicationController
respond_to :json
def index
hash = { :ok => true }
respond_with(hash)
end
end
It looks like you're conflating the old respond_to do |format| style blocks with the new respond_to, respond_with syntax. This edgerails.info post explains it nicely.
class AppController < ApplicationController
respond_to :json
def index
hash = { :ok => true }
respond_with(hash.as_json)
end
end
You should never use to_json to create a representation, only to consume the representation.
format.json { render json: { ok: true } } should work
This was very close. However, it does not automatically convert the hash to json. This was the final result:
class AppControlls < ApplicationController
respond_to :json
def start
app.start
respond_with( { :ok => true }.to_json )
end
end
Thanks for the help.
For those getting a NoMethodError, try this:
class AppController < ApplicationController
respond_to :json
...
def start
app.start
render json: { :ok => true }
end
end

Resources