can we render an array to ajax call directly in Rails? - ruby-on-rails

I am calling below method in an ajax call. I expect this method to return me an array so that I can loop through in my ajax call for a desired result.
Normally we render partial or text . i am not sure how to render an array. could some one please help me out . I know that render text: for arrays will not work .
def get
#bookmarks = Project.get(params[:username])
render text: #bookmarks
end

You should render it as a JSON object:
def get
#bookmarks = Project.get(params[:username])
render json: #bookmarks.to_json
end

Related

How to use Jbuilder to save output for later

I want to save json into a database field for later use. How should I go about that with Jbuilder?
I want to use an item's show template, passing in the object, #item to save the output for that Item into the database for later use.
I got some output with the following code:
view_paths = Rails::Application::Configuration.new(Rails.root).paths["app/views"]
av_helper = ActionView::Base.new view_paths
include Rails.application.routes.url_helpers
#job = Job.find(239)
output = av_helper.render(file: '/api/jobs/show.jbuilder', locals: {:#job => #job})
How can I render the saved json directly from the controller?
Add this for the action code in the controller
def show
#job = Job.find(params[:id])
render :inline => #job.json_output
end
render_to_string
Raw rendering of a template to a string.
It is similar to render, except that it does not set the response_body
and it should be guaranteed to always return a string.
Also if you're doing it from a controller there you can just use the controller to render it:
class JobsController
def create
#job = Job.new(item_params) do |job|
job.my_json_attribute = render_to_string(:show, locals: { :#job => job})
end
if #job.save
redirect_to #job
else
render :new
end
end
end
But this seems like a pretty overcomplicated and flawed way to handle something that can be done with e-tag caching and a reverse proxy or even low level caching. Especially since you would have to repeat the logic when updating the item.

Insert another field into GET response JSON

I have the following code that responds to GET /something.json:
def index
#something = Something.all
respond_to do |format|
format.json { render json: #something }
end
end
That runs a SELECT * FROM something in the database, formats the result into a JSON, and responds with it.
The request might ask for another field through a query parameter, which is in a different table than something. I managed to retrieve the desired field doing this:
def index
#something = Something.all
if params[:get_field_from_some_other_table] == "true"
#something.each do |i|
some_other_table = SomeOtherTable.find(i.some_other_table_id)
the_field_i_want = some_other_table.the_field
end
end
respond_to do |format|
format.json { render json: #something }
end
end
But I haven't found a way to add the field to the JSON string. How can I do that? Or is there a better way to retrieve the field with the contents of the something table through a JOIN or something like that?
something and other_table should be related at active_record somehow... maybe a has_one?
Try that and then just use #something.all.includes(:other_table_attribute)
Apart from that, please post your code properly with some readable examples, that helps a lot and will give you faster responses :)

Render different controller methods as JSON in Rails 5.2

I have a resource that renders as JSON perfectly fine at localhost:3000/gins.json from #gins = Gin.order(name: :desc).
Which will return ALL gins. However, I'd like to have a JSON response that only returns the last 4 gins, to use elsewhere. In the controller I also have:
#latestgins = Gin.order("created_at DESC").first(4)
The above would work in an index.html.erb view with <%= #latestgins.name %>, but how do I get the JSON for this? I have tried render json: #latestgins but navigating to localhost:3000/latestings.json, of course, gives a routing error.
I suspect I'm attacking this in completely the wrong way, but only just starting out with Rails API.
you can add respond to format json in your index method:
def index
#gins = Gin.order(name: :desc)
#latestgins = Gin.order("created_at DESC").first(4)
respond_to do |format|
format.html
format.json { render json: #latestgins }
end
end
your #latestgins is now available here : localhost:3000/gins.json
Edit
If you want a custom route to display your data, just add it in your routes:
defaults format: :json do
get 'last4gins', to: "gins#index"
end
Your data for the last 4 entries is available at http://localhost:3000/last4gins.json, at http://localhost:3000/last4gins but also at localhost:3000/gins.json
If you want to keep the gins index route clean, you can also create a custom method and remove the #latestgins from your index:
# routes
get 'last4gins', to: "gins#last4gins"
#controller
def index
#gins = Gin.order(name: :desc)
end
def last4gins
#latestgins = Gin.order("created_at DESC").first(4)
render json: #latestgins
end
Now the data is no more available at /gins.json

Rails - adding variable to JSON?

I'm using this method to pass back outfits from an ajax call:
def givemeoutfits
if current_user
#outfits = Outfit.search(params[:search],1000000,1,1000000,1,1000000,1,1000000,1).page(1).per(7).results
#results = Outfit.search(params[:search],1000000,1,1000000,1,1000000,1,1000000,1).page(1).per(7).results.total_count
if request.xhr?
render status: 200, json: #outfits
end
end
end
I want to add the integer 'results' to the json produced by the #outfits and returned to the ajax call. How can I do this?
Are you just wanting to include #results in the returned JSON object, like this?
render status: 200, json: {
outfits: #outfits,
results: #results
}
Then, in your javascript, you can interact with both keys.

How to return JSON or Ruby hash from controller?

Please consider the following method in a controller:
def get_navigation_from_session
respond_to do |format|
format.json { render json: session[:navigation]}
end
return session[:navigation]
end
What I want it to do is respond to an Ajax call and send the navigation hash if it's being asked for it. If not, I just want it to return the hash to the ruby code that needs it. This obviously isn't working. How can I fix the above method to accomplish this goal?
Thank you
# this is your action method, supposed to be called via your request cycle with rendering
def get_navigation_from_session
respond_to do |format|
format.json { render json: get_navigation_hash_from_session }
end
end
# a getter - maybe higher up in controller hiararchy
def get_navigation_hash_from_session
session[:navigation]
end

Resources