This seems like a duplicate question but the answers on the others posts don't seem to work for my issue here.
I'm needing to render two JSON items here within my index method in my controller:
def index
#user = User.all
#libraries = Library.all.order(:created_at)
user_cards = current_user.libraries
render :json => #libraries, :include => :user
render :json => user_cards
end
I attempted to do it this way (failed with a 500 error):
render :json => #libraries, user_cards, :include => :user
And I also attempted to do it this way (also failed with a 500 error): render :json => #libraries :include => [:user, :user_cards]
UPDATE
This is the most recent attempt as rendering the json properly:
def index
#user = User.all
#libraries = Library.all.order(:created_at)
user_cards = current_user.libraries
render json: {
user_cards: user_cards,
libraries: #libraries.as_json(include: [:user])
}
end
The issue with this is that I am now getting an error on libraries throughout my application as it stands. If I simply just render json like I originally had it (render :json => #libraries, :include => :user), I do not get this error. So, I'm assuming the way I have it is still not correct. The exact error on libraries is being called within one of my React components where I use filter:
Error: Uncaught TypeError: this.props.librarys.filter is not a function
Error Location:
let filteredCards = this.props.librarys.filter(
(library) => {
return library.title.toLowerCase().indexOf(this.state.search.toLowerCase()) !== -1 || library.desc.toLowerCase().indexOf(this.state.search.toLowerCase()) !== -1
}
)
Controller can only return one response, you can achieve this with combining this two returns into one:
respond_to do |format|
format.json { render json: { user_cards: user_cards,
libraries: #libraries } }
end
Related
I am passing the basic URL required to call OLA API with x app token in HTTParty, but it gives this error:
{"code":"invalid_partner_key","message":"Partner key is not authorized"}
Here is the code:
require 'rubygems'
require 'httparty'
class ProductsController < ApplicationController
def index
lat = params[:lat].to_s
long = params[:long].to_s
#results = HTTParty.get("https://api.uber.com/v1/products?server_token=my_token&latitude="+lat+"&longitude="+long).parsed_response
#result1 = HTTParty.get("https://devapi.olacabs.com/v1/products?X-APP-TOKEN=my_token&pickup_lat=12.9491416&pickup_lng=77.64298").parsed_response
respond_to do |format|
format.json { render :json => JSON.parse(#results) }
format.json { render :json => JSON.parse(#result1) }
format.html { render "index.html.erb" }
end
end
end
Why is this happening, and how do I fix it?
Going through the olacabs docs, your X-APP-TOKEN should be passed as a header and not along with the payload. So you should be doing something like this
query = {
"pickup_lat" => 12.9491416,
"pickup_lng" => 77.64298
}
headers = {
"X-APP-TOKEN" => your_token
}
#result1 = HTTParty.get(
"https://devapi.olacabs.com/v1/products",
:query => query,
:headers => headers
).parsed_response
I didn't test this out but should give a good start to figuring your issue out.
I have this structure
user
-> profile
-> address (table)
-> workplace (table)
and i have this code that does not work as expected, it does not output the address nested association
def index
#users = User.all
render json: #users.as_json(include:
[:profile => {
:include => :address,:include =>:workplace
}
]
)
end
i managed to make it work here is the answer for future reference
def index
#users = User.all
render json: #users.as_json(include:
[:profile => {
:include => [:address,:workplace]
}
]
)
end
In my Case model (case.rb) I have a few after_create callbacks. One of which is not functioning as expected.
By that I mean when I run it in the console, it works, but when creating it in the controller via an HTTP request, it does not.
Model code (the problem is with :create_case_users not working):
after_create -> { redis_check(true) },
:create_case_users,
:create_manager,
:pusher_trigger
And the create_case_users method:
def create_case_users
cus = CaseUser.where(:case_id => self.id, :is_age => 1)
cus.each do |cu|
connections = Connection.where({ :cases => 1, :con_id => cu.user_id })
connections.each do |connection|
if connection.user_id && connection.connection_id
case_user = CaseUser.new
case_user.case_id = self.id
case_user.user_id = connection.user_id
case_user.email = connection.cases_emails
case_user.is_age = 0
case_user.cm = 0
case_user.save!
end
end
end
end
When running the above snippet in the console of my app, specifying the Case to run it for, it works & creates the records I expect.
When I POST to /api/v1/cases, it hits this controller action:
#case = Case.new(case_params)
#case.current_user(#current_user)
if #case.save
render :json => #case,
:root => "case",
:status => :created,
:location => #case,
:serializer => CaseShowSerializer,
:current => #current_user
else
render :json => #case.errors,
:status => :unprocessable_entity
end
What could be the problem? The after create callback after create_case_users runs and functions as expected, meaning create_case_users isn't returning false.
Edit:
When running Case.find(500).create_case_users in the console it works.
This is a relatively simple one and I'm pretty sure its just syntax.
Im trying to render multiple objects as json as a response in a controller. So something like this:
def info
#allWebsites = Website.all
#allPages = Page.all
#allElementTypes = ElementType.all
#allElementData = ElementData.all
respond_to do |format|
format.json{render :json => #allWebsites}
format.json{render :json =>#allPages}
format.json{render :json =>#allElementTypes}
format.json{render :json =>#allElementData}
end
end
end
Problem is I'm only getting a single json back and its always the top one. Is there any way to render multiple objects this way?
Or should I create a new object made up of other objects.to_json?
you could actually do it like so:
format.json {
render :json => {
:websites => #allWebsites,
:pages => #allPages,
:element_types => #AllElementTypes,
:element_data => #AllElementData
}
}
in case you use jquery you will need to do something like:
data = $.parseJSON( xhr.responseText );
data.websites #=> #allWebsites data from your controller
data.pages #=> #allPages data from your controller
and so on
EDIT:
answering your question, you don't necessarily have to parse the response, it's just what I usually do. There's a number of functions that do it for you right away, for example:
$.getJSON('/info', function(data) {
var websites = data.websites,
pages = data.pages,
...
});
I've looked at similar posts but can't seem to quite figure it out.
I have the following function which works just fine. The Listing model has a foreign key called price_id which maps to the Price model and its price_range column. Price_id is returned as part of the message object in the JSON response.
How can I return the corresponding price_range value from the association instead of the price_id value (as part of the message obj, and keep the other attributes)?
def update
#listing = Listing.find(params[:listing][:id])
#if params were passed in for updating
if #listing.update_attributes(params[:listing])
#should we return the whole thing or just what's needed?
json_response = {
"success" => #listing.save, #save to DB and assign true/false based on success...
"message" => #listing.attributes #USE attributes to show output the content of the #message obj, and not another object called "message"
}
respond_to do |format|
#json response
format.html { render:json => json_response }
format.xml { render :xml => #listing }
#normal response. Consider leaving this for now?
#format.html { render :action => "detail" } #refresh this page, with new data in it. Consider trying to use redirect instead?
#format.xml { head :ok }
end
end #end if
end
add a method in your Listing model with the price_range and call it in serializable_hash
class Listing
def price_range
price.price_range
end
end
Like explain on comment you can use delegate instead this method :
class Listing
delegate :prince_range, :to => price
end
In you controller you can now do :
json_response = {
"success" => #listing.save, #save to DB and assign true/false based on success...
"message" => #listing.serializable_hash(:methods => [:price_range])
}
Based on what I read in this article, you should be able to do this:
class Listing
def as_json
super(:include => :price)
end
end
Then in your controller:
json_response = {
"success" => #listing.save,
"message" => #listing.as_json
}
If I understand correctly, you want to add #listing.price.price_range value to the "message" ?
If so, try this:
"message" => #listing.attributes[:price_range] = #listing.price.price_range