How can I render two objects using "render json:" in a Controller? - ruby-on-rails

I have two objects that I want my index action to return, but I'm struggling to find the syntax to return them both at the same time.
def index
last_day_for_jack = Tacobell.where(owner: "Jack")
last_day_for_pete = Tacobell.where(owner: "Pete")
render json: { last_day_for_jack last_day_for_pete }
end

Related

How can I update serialized data in a Rails/MariaDB backend?

Currently, I have some QueuedImages that become GalleryImages once certain conditions are met.
#image = GalleryImage.new(image_params.except(:tags))
#image.user = current_user
#queued = QueuedImage.new(user: current_user)
#queued.image = #image
Before saving this method, transform the images into JSON:
def image_to_json
self.image_data = #image.to_json(include: :plain_images)
end
I'm trying to update the serialized hash/JSON like this:
def update
#queued = QueuedImage.find(params[:id])
hash_as_string = #queued.image_data
i_data = JSON.parse(hash_as_string.gsub('=>', ':'))
i_data["title"] = params["title"]
i_data["description"] = params["description"]
i_data["folder_id"] = params["folder_id"]
i_data["nsfw"] = params["nsfw"]
i_data["tags"] = params["tags"]
#queued.image_data = i_data
if #queued.save
render json: #queued, scope: current_user
else
render json: #queued.errors.as_json(full_messages: true), scope: current_user, status: :unprocessable_entity
end
end
Which throws me a parse error, what am I doing wrong?
How can I properly update the serialized string?
The thing is that when it transforms from a QueuedImage to a GalleryImage, another method takes that data and evaluates it and creates the new GalleryImage, so it has to be in the exact format, and I believe what I'm doing in the update method is wrong, even though I save it as a string in the DB.

Rails how to return single JSON object instead of array of JSON objects?

I am limiting to 1, so I thought it would simple return an object in this case the same as .find_by_email
Code:
# GET /users/:identified/type/:social_type
# Returns a single record - so limit 1
def find
#user = User.where("identified = ? AND social_type = ?", params[:identified], params[:social_type]).limit(1)
if not #user.empty?
render json: #user.as_json, status: :created
else
render json: #user, status: :not_found
end
end
Current Response:
[{"id":7,"voy_num":null,"voy_pin":null}]
How can ensure I return a single JSON object?
To get the single object, use first with where like this:
#user = User.where("identified = ? AND social_type = ?", params[:identified], params[:social_type]).first

Rails Render JSON Object instead of entire array

In my controller I have the present code that results in a JSON array, even though there is only one result:
def getSharedSpecial
#result = Campaign.find_by_sql("SELECT
id
,name
,image
,ad_caption
,ad_details
FROM campaigns
WHERE id = " + params[:shared_campagin_id].to_s + "
LIMIT 1;")
respond_to do |format|
format.html
format.json { render json: { special_shared: #result }}
end
end
returns:
"special_shared":[
{
"id":41,
"name":"tester the way",
"image":{
"url":"/uploads/campaign/image/41/Gilded_pic.jpg"
},
"ad_caption":"yfftitu6",
"ad_details":"jku"
}
]
}
As can be seen given the [], this is a JSON array.
How can I create just an object and not an entire array?
The problem is that find_by_sql always returns an array even though you are only looking for a single record. There is no need to use find_by_sql and you've opened yourself to SQL injection attacks by doing so, so just write the finder the traditional way:
#result = Campaign.select(:id, :name, :image, :ad_caption, :ad_details).find(params[:shared_campagin_id])

Filter controller result based on params

I'm trying to filter the results that are returned from my index view based on optional params. My code is working for the first param, sinceDate. But for the second param, searchQeury, nothing is filtered out.
_controller.rb
def index
since = params[:sinceDate]
query = params[:searchQuery]
#articles = Comfy::Cms::Page.published.all
if since
#articles = #articles.reject{ |a| a[:created_at] < Date.parse(since) }
end
if query
#article = #articles.select{ |a| a[:label].match(/#{query}/i) }
end
end
Is it possible that the problem is a typo?
In the line after "if query", it should be perhaps #articles instead of #article.

Geojson data format output properly in a rails app

i m trying to implement a service that displays data in geojson format.
I hit my database with this :
sql =
"select ST_AsGeoJSON(boundaries)
from cluster_shapes
where category = '#{params[:category]}'
and area_id =
(select id
from areas
where name = '#{params[:city]}' )"
connection = ActiveRecord::Base.connection
#clusters = ActiveRecord::Base.connection.execute(sql)
respond_to do |format|
format.json { render json: #clusters }
end
And I get ugly results that is not valid geojson
[
{
st_asgeojson: "{"type":"Polygon","coordinates":[[[23.819537,38.039409],[23.81892,38.04068],...}"
,
st_asgeojson: "{"type":"Polygon","coordinates":[[[23.919537,38.039409],[22.81892,38.04068],...}"
,
...
If I remove the ugly part st_asgeojson and make it look like this , it is valid geojson.
{"type":"Polygon","coordinates":[[[23.819537,38.039409],[23.81892,38.04068],[23.820912,38.040237],[23.8209752169298,38.0400047630785],[23.8209519774174,38.0399755885062],[23.8205266,38.0394558],[23.819537,38.039409]]]}
So the question is how do i get rid of "st_asgeojson" ,or am i doing it wrong ?
PS:A model exist, if query is modified the result is pretty the same.
It seems like what you want is simply nested inside your #clusters json, so you can simply parse it out...
instead of:
format.json { render json: #clusters }
you should change it to
format.json { render json: #clusters[0].st_asgeojson }
Or if you are expecting more than one result to be returned from you sql query, try
format.json { render json: #clusters.map {|x| x.st_asgeojson }}

Resources