How to paginate with act_as_api rails 3? - ruby-on-rails

Hi I'm using act_as_api to render my xml and json, all is well until i want to add the will_paginate fields into my outputs.
Has anyone been successful?

Found the solution in one of the feature requests for acts_as_api gem
format.xml { render_for_api :template,
:xml => #posts ,
:root => :posts,
:meta => {:current_page => #posts.current_page,
:total_pages => #posts.total_pages,
:per_page => #posts.per_page }}
So there you have it, with meta support, you can add whatever you want, in this case I wanted my pagination data in there.
Metadata support - Add pagination fields

as of today, there is a wiki entry about this topic on github:
https://github.com/fabrik42/acts_as_api/wiki/Add-meta-data-%28like-pagination-info%29-to-your-response

Related

TinyMCE Spellcheck expected JSON Response in Rails

I am using TinyMCE and I have rolled my own spellchecker using FFI-Hunspell.
I am just rendering this hardcoded response but when I click the spell check button in the WYSIWYG editor, it says that there aren't any misspelled words.
render :json => {:id => "#{params[:id]}", :result => {"presents" => ["presnts"], "motor" => ["moors"]}}.to_json
So, what is the JSON supposed to look like?
I am using the tinymce_rails gem. I would have thought it was using the newer version. Anyways, I found this link that describes in detail how the request/response should look: https://github.com/spohlenz/tinymce-rails. Effectively, the response for the older version of tinyMCE is this:
render :json => ({:id => nil, :result => ['badk', 'wirds'], :error => nil}).to_json
Also, it actually uses a second request to get the suggestions. And those should look like:
render :json => ({:id => nil, :result => ['bad', 'bed'], :error => nil}).to_json

Convert two models attribute in a json response

I am on ruby on rails and i have two models, the goal is to do a search of the website on two models, i am using twitter typeahead but the issue i have is the json has to be one object.
I am not sure what is the best way to convert my two objects into one. Here the code
#users= Search.user(params[:query])
#articles= Search.article(params[:query])
respond_to do |format|
format.html # index.html.erb
format.json {
render :json => {
:art=> #articles.map(&:title),
:user=> #users.map(&:first_name)
}}
end
end
I am not sure what the best way or i can't seem to find the best documentation to merge these two models into one. I dont know if to_json, as_json, or concat would be the best.
The idea is to have a result of the following json from
{"art":["John","Serge","Dean","feng","Heather"],"user":["Ontario high school teachers drop next week's walkout plan","Air Canada to appeal Quebec court ruling on Aveos"]}
To the following
{"result":["John","Serge","Dean","feng","Heather", "Ontario high school teachers drop next week's walkout plan","Air Canada to appeal Quebec court ruling on Aveos"]}
So if you want to get an array of both users and articles:
respond_to do |format|
format.json { render :json => {:art => #articles,
:user => #users }}
end
end
Based on your edit:
format.json {
render :json => {
result => #articles.map(&:title) | #users.map(&:first_name)
}}
Based on last comment, just trap the nil issue:
format.json {
render :json => {
result => (#articles.map(&:title) || []) | (#users.map(&:first_name) || [])
}}
Can I suggest that you use a JSON view template. There are many options for you but the two most popular are RABL and JBuilder. I can highly recommend the RABL gem.
There is a reason for their popularity, they make rendering json a breeze
You can find the RABL gem here https://github.com/nesquena/rabl
You can find the JBuilder gem here https://github.com/rails/jbuilder
There are excellent railsasts on both of them showing how to use them.
RABL
http://railscasts.com/episodes/322-rabl
JBuilder
http://railscasts.com/episodes/320-jbuilder
I favour RABL purely out of personal preference you should look at both options to see which best suits you.
Adding a gem is not normally something I would recommend but I think you will find that either of these solutions will match your needs

Rails - Paperclip url in JSON along with other attributes

I've followed Ryan Bates' screencast on using jQuery Tokeninput for an auto-completing list for a many-to-many association. Now I want to pull in a photo for each result. I'm using Paperclip and get the url's passed into a JSON file by doing this in the controller:
format.json { render :json => #users.map(&:photo_url) }
Ryan's code for passing the attributes into a JSON file is this:
format.json { render :json => #users.map(&:attributes) }
But how can I combine the two to display both the :attributes and :photo_url methods in the JSON file?
I've tried different things, including the below code, but nothing seems to work. It seems as if there can only be one method called on .map?
// Doesn't work
format.json { render :json => #users.map(&:attributes, &:photo_url) }
// Doesn't work
format.json { render :json => #users.map(&:attributes).map(&:photo_url) }
Does this help? (Note - I'm just returning from a night out and am not 100%, so I might be misunderstanding your question entirely.)
This creates an array of arrays: The first element in the array contains the user's attributes, and the second contains the photo URL:
#users.map {|u| [u.attributes, u.photo_url]}
This creates a hash - just like the above array. But the first element is named "attributes" and the second is named "photo_url".
#users.map {|u| {:attributes => u.attributes, :photo_url => u.photo_url}}
Try plugging one or both of those in. They should work for you.
(E.g. format.json { render :json => #users.map {|u| [u.attributes, u.photo_url]} }).
Edit:
Just had another thought.
You can merge the two into one collection (so that you'll have it all in one hash instead of separate elements in an array):
#users.map {|u| u.attributes.merge(:photo_url => u.photo_url)}
That'll add photo_url as a key to the attributes hash. It might work more easily for whatever code you've written to read the JSON.
In case of this being helpful to anyone, i find out a nice way to do this:
class MyModel < ActiveRecord::Base
has_attached_file :avatar, :styles => { :large => "500x500#", :medium => "300x300#", :small => "100x100#", :thumb => "50x50#" }
def as_json(options)
json = super
self.avatar.styles.each do | format |
json = json.merge({"avatar_"+format[0].to_s => self.avatar(format[0])})
end
json
end
end
You can then simply call
render :json => #my_model
Also working while rendering collections.
It is then possible to do some conditional rendering with as_json(options), with something like:
model_to_json = #my_model.to_json(:nested => true)
render :json => model_json

RAILS3: to_JSON with multiple objects and includes

def list
#rings = Ring.order("RAND()")
#JSON RENDERING
render :json => #rings.to_json(:include => [:variations, :stones]), :callback => params[:callback]
end
def show
#showring = Ring.includes(:stones, :variations).find(params[:id])
#other_rings = Ring.select([:id, :stone_count]).where(:style_number => #showring.style_number).reject{ |ring| ring == #showring}
#JSON RENDERING
render :json => {#showring.to_json(:include =>[:variations, :stones]), :other_rings => #other_rings}, :callback => params[:callback]
end
My list view rendering works fine, but when i want to do a show view, with two objects, and showring with includes won't render proper JSON. It is quoting everything in the object with the includes...
JSON output looks like this:
showring => "{"available":"yes","eng...9","stone_y":"149.4"}]}"
other_rings => properly rendered object
On a seperate note, if i have already added the includes to #rings object, why do i then again have to add the association in the "to_json" method?
When you do
render :json => {:show_ring => #showring.to_json(:include =>[:variations, :stones]), :other_rings => #other_rings}
Rails is converting #showring to json (ie getting back a string representation), i.e. the value is the string literal. Instead do
render :json => {:show_ring => #showring.as_json(:include =>[:variations, :stones]), :other_rings => #other_rings}
as_json does all the work of turning the object into a hash but without the final step of turning into a string
if you are going to invest more time in building more JSON objects, you should look into a gem called rabl. It makes building JSON very simple, good for customization which then is good for building API.

Automatically generate html file from an erb file using Ruby on Rails

I have a RoR app that tracks the status of values in a database and displays the visualization of this information in the form of charts, graphs, and tables generated by an erb file. This is very handy and I am able to save snapshots of the status' of the DBs by simply saving the page when I open it in a browser. What I would like, however, is for my app to automatically do this saving for me on a nightly basis. I assume this is possible but I'm not having much luck with this so far. Any suggestion on this point would be very helpful.
you can always use render_to_string method to render your erb. For example you need to render show.html.erb for show action in statistics controller:
my_page = render_to_string :controller => 'statistics', :action => 'show', :layout => 'application'
but firstly you should define all it's variables which you use int show view.
#data = Data.last_data
#users = User.active
enter code here
my_page = render_to_string :controller => 'statistics', :action => 'show', :layout => 'application'
snapshot = Snapshot.new :page => my_page
snapshot.save
API: http://apidock.com/rails/ActionController/Base/render_to_string
You can use whenever: https://github.com/javan/whenever
From the readme:
Whenever is a Ruby gem that provides a
clear syntax for writing and deploying
cron jobs.
There is also delayed-job: https://github.com/tobi/delayed_job
From the Readme:
Delayed_job (or DJ) encapsulates the
common pattern of asynchronously
executing longer tasks in the
background.

Resources